11

cat ./1.sh

#!/bin/bash
echo $1
set var1 = $1
echo var1 is $var1

kostas@elem:~/1$ argument1 var1 is

How to set var1 from first commandline argument?

1 Answer 1

34

The correct assignment is simply the following, with no spaces on either side of the equal sign:

var1=$1

The command set var1 = $1 actually does the following:

  1. Sets the value of $1 to "var1"
  2. Sets the value of $2 to "="
  3. Sets the value of $3 to the original first parameter $1.
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, Im newbie in bash
+1. To summarize: Do not use set for variable assignment (it serves a different purpose - see help set); instead, use <varname>=<value>, and be sure not to use whitespace on either side of the =.
@glennjackman, nowhere does that link explain how to set a variable.
You're right. Amazing it took 6 years for someone to point that out.
@Daniel It's fine; a parameter expansion on the RHS of an assignment is not subject to word-splitting or pathname expansion. If you are more comfortable doing so, var="$1" is fine as well; the quotes are removed as usual before assigning the result to var.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.