File content into windows variable - PowerShell - linux

I'm new in PowerShell, I want to put the content of a file into a windows variable.
In fact I need the equivalent of those linux commans on windows
testvar=$(cat test.txt)
echo $testvar

Actually, because cat and echo are aliased to Get-Content and Write-Output respectively, that code will work, though you need to prefix testvar with a $, so it reads $testvar. It can also be written with proper cmdlets and remove the unnecessary subexpression:
$testvar = Get-Content test.txt
Write-Output $testvar
And you really don't need to use Write-Output, either. simply writing $testvar on its own will default to the output stream.

$testvar = Get-Content "test.txt"
Write-Host $testvar
cat is an alias in powershell to Get-Content,
echo is an alias to Write-Output

Related

Powershell for Linux: Combining commands with pipe sign doesn't work

Any way to concatenate commands in Powershell for Linux?
This is what I'm trying to run:
pwsh -Command Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"
So, run the Invoke-ScriptAnalyzer, convert the results to Json and save the result to test.json.
It doesn't recognize anything after the | sign:
./test.sh: line 1: ConvertTo-Json: command not found
./test.sh: line 1: Out-File: command not found
I need this to go in a bash script, hence the need to launch pwsh with the -Command option.
Any ideas?
Thanks
As written, your | symbols are interpreted by your Linux shell (such as bash), not by PowerShell.
There are two soutions:
Preferably, quote the entire -Command argument (a '...' string in a POSIX-compatible shell such as bash uses the string's content verbatim):
pwsh -Command 'Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"'
Alternatively, individually \-escape all Linux-shell metacharacters that you want to pass through verbatim, such as \| and \" in this case:
pwsh -Command Invoke-ScriptAnalyzer -Path . \| ConvertTo-Json \| Out-File -FilePath \"/home/administrator/scripts/test.json\"
Note: In this case, pwsh receives multiple arguments after -Command. However, PowerShell simply joins them before interpreting the result as PowerShell code.
This differs from the command-line processing of POSIX-compatible shells, which interpret the first post--c argument as an implicit, ad-hoc script, with additional arguments getting passed as verbatim arguments to that script, accessible as usual as $1, ...

Powershell newline in script argument not working

I have this little script i use to call it with differernt RegEx arguments for replacing text in files:
param ($file, $fnd, $rpl)
(Get-Content $file -Raw) -replace $fnd , $rpl | Set-Content $file
problem is if i pass it an argument containing a new line escape code `r`n like so:
powershell -File txt-replace.ps1 "file path" "RegEx_pattern" "line1`r`nline2"
will write on file:
line1`r`nline2
instead of:
line1
line2
BUT IF i define $rpl inside the script, with the exact argument content, it works:
$rpl = "line1`r`nline2"
writes:
line1
line2
Also works if i run it as a command in widows terminal:
powershell -command "(Get-Content file_path | Out-String ).Trim() | ForEach-Object {$_ -replace 'RegEx_pattern' , \"line1`r`nline2\"} | Set-Content file_path "
i debugged it further inside the script:
write-host $rpl
writes in terminal:
line1`r`nline2
BUT
$rpl= "line1`r`nline2"
write-host $rpl
writes in terminal:
line1
line2
What am i missing?
It is simplest to just use -Command parameter.
powershell -Command ".\txt-replace.ps1 \"file path\" \"RegEx_pattern\" \"line1`r`nline2\""
The backslash escapes are for the CMD shell. Since you want those quotes passed to PowerShell, we need to escape them first at the CMD shell layer. Otherwise, CMD will think they are surrounding strings for it to interpret.
When using -File the script arguments are passed literally after interpretation by the current shell. CMD doesn't know what the newline characters are so they just remain `r`n and then are passed literally as one of the string arguments.
When using -Command, the command string is treated as if it were entered at a PowerShell prompt.
See About_PowerShell.exe for more information.

TCSH error in foreach loop: files.list: Command not found

I am trying to pass a user-input variable (a file name) into a foreach loop in tcsh. The user entered variable is, for example, "files.list" (saved in the same folder as the Shell Script is saved, and is being run from).
Here is my code:
#! /usr/bin/tcsh -f
echo please enter files list
set x = $<
foreach i ('$x')
echo $i
end
What I want is for each of the words in "files.list" to be output to the screen. Files.list contains 5 lines, each with a file name.
myScript22.sh
Mad45.sh
Number32.sh
killBill.sh
gotMilk.sh
bugslife.sh
I get an error - "foreach: Words not parenthesized."
Could it be that 'cat $x' isn't calling the x variable correctly? If so, how do I get the file set up so it's contents can be looped thru?
Any help is appreciated!
If you really really really really have to use tcsh, then the following is the propper way to do it:
#!/usr/bin/tcsh -f
echo please enter files list
set x = $<
foreach line (" `cat $x` ")
echo "$line"
end
It is important to see that the cat command is between <double-quotes>. The difference is that otherwise, the foreach statement will read word-by-word, while the double-quoted version will read line-by-line. The logic of this is ... questionable. Also, I quoted the variable line in the echo statement, because it will actually complain when it hits an empty line.
In bash, you would just do the following nice thing:
#!/usr/bin/env bash
echo "Please enter files list"
file=""
while [[ ! -e $file ]]; do read -r file; done
while read -r line; do
echo "$line"
done < "$file"
Very important reads:
CSH PROGRAMMING CONSIDERED HARMFUL
Top Ten Reasons not to use the C shell
For reference purposes, I was missing the cat command, before the $x.
So the code should read:
#! /usr/bin/tcsh -f
echo please enter files list
set x = $<
foreach i ('cat $x')
echo $i
end
You have two mistakes in your tcsh script:
Missing cat command in front of the filename in your foreach condition.
Use of straight single quotes(' ') instead of backquotes (``) in your foreach condition.
The following script should work for you.
#!/usr/bin/tcsh -f
echo please enter files list
set x = $<
foreach i(`cat $x`)
echo $i
end

Linux tr command

I'm relatively new to programming in c-shell and I'm having a problem with the tr command. When I execute the script, the error message I receive is "tr command not found". I'm also trying to display the contents of a file in foreach loop that I've assigned to a variable. Would this actually only print the name of the file path or its contents? Here's my code :
#! /bin/csh
set path = /home/students/fall2012/crn12143/ford/friend_list
foreach i ($path)
echo $i | tr '[a-z]' '[A-Z]'
end
You are breaking the path so it can no longer find tr. Change the path like:
set path=(/home/students/fall2012/crn12143/ford/friend_list $path)
Since you aren't really using path like it should be used, you should consider renaming that variable to something else.
If you want to still remove most of the path, use the full path for the tr command:
echo $i | /path/to/tr '[a-z]' '[A-Z]'
You are redefining the PATH envrionment variable, which is not good.
You should instead use a different variable name like:
set folder = /home/students/fall2012/crn12143/ford/friend_list

Search log file for string with bash script

I just started learning PHP. I'm following phpacademy's tutorials which I would recommend to anyone. Anyways, I'm using XAMPP to test out my scripts. I'm trying to write a bash script that will start XAMPP and then open firefox to the localhost page if it finds a specific string, "XAMPP for Linux started.", that has been redirected from the terminal to the file xampp.log. I'm having a problem searching the file. I keep getting a:
grep: for: No such file or directory
I know the file exists, I think my syntax is wrong. This is what I've got so far:
loaded=$false
string="XAMPP for Linux started."
echo "Starting Xampp..."
sudo /opt/lampp/lampp start 2>&1 > ~/Documents/xampp.log
sleep 15
if grep -q $string ~/Documents/xampp.log; then
$loaded=$true
echo -e "\nXampp successfully started!"
fi
if [$loaded -eq $true]; then
echo -e "Opening localhost..."
firefox "http://localhost/"
else
echo -e "\nXampp failed to start."
echo -e "\nHere's what went wrong:\n"
cat ~/Documents/xampp.log
fi
In shell scripts you shouldn't write $variable, since that will do word expansion on the variable's value. In your case, it results in four words.
Always use quotes around the variables, like this:
grep -e "$string" file...
The -e is necessary when the string might start with a dash, and the quotes around the string keep it as one word.
By the way: when you write shell programs, the first line should be set -eu. This enables *e*rror checking and checks for *u*ndefined variables, which will be useful in your case. For more details, read the Bash manual.
You are searching for a string you should put wihtin quotes.
Try "$string" instead of $string
There are a couple of problems:
quote variables if you want to pass them as a simple argument "$string"
there is no $true and $false
bash does variable expansion, it substitutes variable names with their values before executing the command. $loaded=$true should be loaded=true.
you need spaces and usually quotes in the if: if [$loaded -eq $true] if [ "$loaded" -eq true ]. in this case the variable is set so it won't cause problems but in general don't rely on that.

Resources