To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'
$1 is the first argument (filename1) $2 is the second argument (dir1)
For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.
Try:
pwd=`pwd`
or
pwd=$(pwd)
Notice no spaces after the equals sign.
Also as Mr. Weiss points out; you don't assign to $pwd
, you assign to pwd
.
In shell you assign to a variable without the dollar-sign:
TEST=`pwd`
echo $TEST
that's better (and can be nested) but is not as portable as the backtics:
TEST=$(pwd)
echo $TEST
Always remember: the dollar-sign is only used when reading a variable.
In this specific case, note that bash has a variable called PWD
that contains the current directory: $PWD
is equivalent to `pwd`
. (So do other shells, this is a standard feature.) So you can write your script like this:
#!/bin/bash
until [ "$PWD" = "/" ]; do
echo "$PWD"
ls && cd .. && ls
done
Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*
), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo"
and command substitutions "$(foo)"
(unless you specifically know you have not to).
In the general case, as other answers have mentioned already:
var=value
, not var = value
$
means “take the value of this variable”, so you don't use it when assigning: var=value
, not $var=value
You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.
All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.
It looks something like this:
NUM_PROCS=$(ps -e | sed 1d | wc -l)
I hope that helps add some handy information to this discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With