How to change the value of an argument in a script?
I tried the following small simple script:
#!/bin/bash
$1="bar"
echo $1
But when I run ./script foo
I get error and the value is not changed:
/home/mika/script: line 2: foo=bar: command not found
foo
I know $1 is the first argument you pass to your script. But even like this I want to change its value.
You can use the builtin set
:
#!/bin/bash
set -- "bar"
echo $1
Source and more about: Change a command line argument - bash.
You can't change those variables directly. You could say:
x=$1
echo $x
Then you can use $x
instead
Using $1=bar
will immediately substitute the first parameter for $1
, and you are essentially stating "foo=bar"
, and it is interpreted as a command "foo", not a variable "foo";
Don't use use $1
for this, in bash
, and other shells, $1
is the first argument you pass to your script:
#!/bin/bash
echo $1
If you run the above as foo.sh hello
, it will print hello
since that is the 1st argument. Also, you refer to a variable as var
and to a variable's contents as $var
. So, to get the behavior you are expecting, just use another name for your variable and don't use a $
:
#!/bin/bash
var="bar"
echo $var