5

I'm writing a bash shell script. There's a required first argument and I want to have an optional second argument.

If the second argument is omitted I want it to use the value of the first argument.

Currently I have:

SOMEVAR=${2:-Untitled}

How can I use something like basename $1 instead of Untitled?

1
  • 1
    PS: You might want to use ${2-Whatever} (without the ":") to check that $2 is undefined not empty or undefined. Commented Jul 19, 2011 at 11:26

2 Answers 2

8

You can just do something like SOMEVAR=${2:-$(basename "$1")}. You can do any shell or variable in the optional part.

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

Comments

3

Just use command substitution: $(basename $1), literally instead of Untitled.

However, bash also has the ability to do this without an external process: ${1##*/}

SOMEVAR=${2:-${1##*/}}

3 Comments

The problem with using ${1##*/} shell expansion is that it is not an all encompassing replacement for basename. basename does more than just find the last '/' character.
So ${1##*/} is equivalent to $(basename $1)?
No, ${1##*/} isn't equivalent to $(basename $1). For example, if you had dir=/ and tried ${dir##*/}, you would get nothing, whereas $(basename "$dir") would give you /.

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.