Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to set a variable from argument, and with a default value

Tags:

bash

shell

unix

It is pretty clear that with shell scripting this sort of thing can be accomplished in a huge number of ways (more than most programming languages) because of all the different variable expansion methods and programs like test and [ and [[, etc.

Right now I'm just looking for

DIR=$1 or . 

Meaning, my DIR variable should contain either what is specified in the first arg or the current directory.

What is the difference between this and DIR=${1-.}?

I find the hyphen syntax confusing, and seek more readable syntax.

Why can't I do this?

DIR="$1" || '.' 

I'm guessing this means "if $1 is empty, the assignment still works (DIR becomes empty), so the invalid command '.' never gets executed."

like image 936
Steven Lu Avatar asked Apr 18 '13 04:04

Steven Lu


People also ask

How do you declare a variable with default value?

To provide a default value for a variable, include a DEFAULT clause. The value can be specified as an expression; it need not be a constant. If the DEFAULT clause is missing, the initial value is NULL. When a variable is first declared, its value is set to NULL.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do I assign a variable to a variable in bash?

We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.


1 Answers

I see several questions here.

  1. “Can I write something that actually reflects this logic”

    Yes. There are a few ways you can do it. Here's one:

    if [[ "$1" != "" ]]; then     DIR="$1" else     DIR=. fi 
  2. “What is the difference between this and DIR=${1-.}?”

    The syntax ${1-.} expands to . if $1 is unset, but expands like $1 if $1 is set—even if $1 is set to the empty string.

    The syntax ${1:-.} expands to . if $1 is unset or is set to the empty string. It expands like $1 only if $1 is set to something other than the empty string.

  3. “Why can't I do this? DIR="$1" || '.'

    Because this is bash, not perl or ruby or some other language. (Pardon my snideness.)

    In bash, || separates entire commands (technically it separates pipelines). It doesn't separate expressions.

    So DIR="$1" || '.' means “execute DIR="$1", and if that exits with a non-zero exit code, execute '.'”.

like image 191
rob mayoff Avatar answered Oct 06 '22 09:10

rob mayoff