0

I'm trying to reassign the value of the positional command line argument $1 to another variable to use elsewhere in the script, but it never works. I have put the following code in a new script and found that the value of the new variable is always blank.

dirname = $1
echo "This is \$1:$1"
echo "This is \$dirname:$dirname"

The output of this after running ./test.sh someval is:

This is $1:someval
This is $dirname:

As you can see, 'dirname' is blank, even after being assigned the value of $1. I'm new to bash so likely missing something. Any help is appreciated.

  • Please paste the code **excactly** as it is in your script. If you really had a `dirname = $1` in your script, this would print a single period to stdout. – user1934428 Dec 08 '21 at 13:04
  • `dirname` is command name and cannot be used as a variable name. – DaBler Dec 08 '21 at 13:06
  • It is also unclear, what you are asking: In the title you ask how to re-assign the positional parameters in a script (this would be done using the `set` command), but in the text of your question, you ask how to assign something to a variable. – user1934428 Dec 08 '21 at 13:07
  • Moreover, assign to a variable can be done using `variable=value`, not `variable = value`. – DaBler Dec 08 '21 at 13:08
  • @DaBler : You can use any command name as a variable name, as long as it is syntactically valid as a variable name. If this were not the case, you could simply break a working script, by putting a command with the same name as a variable into the PATH. – user1934428 Dec 08 '21 at 13:08
  • @DaBler It can; this just isn't an assignment statement. It's calling `dirname` with arguments `=` and the expansion of `$1`. – chepner Dec 08 '21 at 13:09
  • @user1934428 That is indeed true. – DaBler Dec 08 '21 at 13:09
  • 1
    Near duplicate of https://stackoverflow.com/q/2268104/1126841, except the attempted variable name *is* a command, so no "command not found" error is raised. – chepner Dec 08 '21 at 13:10

1 Answers1

0

Assignments cannot have whitespace around the =. An assignment is a single word containing a =: the name precedes the (first) =, and the value follows it.

dirname=$1
chepner
  • 497,756
  • 71
  • 530
  • 681