0

I want to set an alias depending on an environmental variable pattern match in 1 line.

I am trying:

[[$HOSTNAME =~ 'q20' ]] && alias a='cd ~/a1' || alias a='cd ~/a99'

but I get -bash: [[uscamwebq20.boston.zipcar.com: command not found

I also tried:

$ [ -z $HOSTNAME =~ q20 ] && alias a='cd ~/a1' || alias a1='cd ~/a99'

but I get -bash: [: too many arguments

2 Answers 2

7
case $HOSTNAME in (*q20*) alias a='cd ~/a1';; (*) alias a='cd ~/a99'; esac

You're getting an error, because spaces are missing after [[ and because -z is to test if a particular string is empty. [[ is a non-standard feature, how it behaves depends on the version of bash. The case structure is POSIX and as written will work in any POSIX shell and any version of bash.

More generally, it's also better to stay away from things like cmd1 && cmd2 || cmd3 as it generally doesn't not do what you want if cmd2 fails.

Also, I don't see the point in putting it all on one line. That's something that's going to go to some rc file, right? Then it will be a lot more legible if on several lines.

case $HOSTNAME in
  (*q20*) alias a='cd ~/a1';;
      (*) alias a='cd ~/a99'
esac

is more legible and portable than:

if [[ $HOSTNAME =~ q20 ]]; then
  alias a='cd ~/a1'
else
  alias a='cd ~/a99'
fi

itself more legible (and more correct) than:

[[ $HOSTNAME =~ q20 ]] &&
  alias a='cd ~/a1' ||
  alias a='cd ~/a99'

itself more legible than

[[ $HOSTNAME =~ q20 ]] && alias a='cd ~/a1' || alias a='cd ~/a99'
1
  • Thanks! Definitely an opinion thing that probably relates to experience level and also just plain preferences. 5 years ago I would have preferred if then, now I prefer the && || for my (yes) .bashrc file. Using such teniques in several places means that my file is now 28 lines long instead of close to 100 and fits on 1 screen which is my preference for readability as I am very visual. Commented Jun 12, 2014 at 13:58
3

You can use the first form but you need to put a whitespace after [[. See:

$ type [[
[[ is a shell keyword

$ help [[
[[ ... ]]: [[ expression ]]
    Execute conditional command.

So your command should look like this:

[[ $HOSTNAME =~ 'q20' ]] && alias a='cd ~/a1' || alias a='cd ~/a99'

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.