0

My bash script bash.sh only contains one line

echo "${abc:=123}"

I learned that := is used to assign default values. So when I run bash.sh abc=abc, I expect the output to be abc.

However, the output is still 123.

Why is that? Am I call the script in the wrong way? Thanks.

2
  • 1
    Replace that with abc=abc ./bash.sh to set abc as an environment variable instead of a positional argument (which nothing in your script currently reads). Commented Oct 1, 2019 at 22:46
  • 2
    BTW, if it doesn't start with a line equivalent to #!/bin/bash, it isn't a bash script at all. (#!/bin/sh scripts also aren't bash scripts; they're POSIX sh scripts, which is a more restricted language). Commented Oct 1, 2019 at 22:47

2 Answers 2

1

Bash positional arguments are set to $1, $2, etc. Change your script to:

abc=$1
echo "${abc:=123}"

this will make it so if the variable abc is unset the default value is echoed but if another value is passed on the command line abc will be set to that value.

Sign up to request clarification or add additional context in comments.

Comments

1

You are passing a parameter and expecting to see it in an environment variable.

If you want to set an environment variable, you can do that before the script name:

$ cat foo
#!/bin/bash
echo "${abc:=123}"

$ ./foo
123

$ abc=hello ./foo
hello

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.