155

I would like to know how can I write if conditions inside a bash script on a single line.

For example, how can I write this on a single line, and then put another one just like it on the next?

if [ -f "/usr/bin/wine" ]; then
    export WINEARCH=win32
fi

I ask this because I have quite a few aliases in my .bashrc and I have the same .bashrc (synced) on multiple systems, but I don't need all aliases on each systems. I put most of them inside if statements, and it is all working beautifully now but they take a lot of space, 3 lines each plus the blank line between them (i like having them easily visible)

I will also use this technique for environment variables as well.

Journeyman Geek
  • 133,878
DELETED
  • 1,701

4 Answers4

232

You would write it as such:

if [ -f "/usr/bin/wine" ]; then export WINEARCH=win32; fi

Note that this could also be written (as suggested by @glennjackman):

[ -f "/usr/bin/wine" ] && export WINEARCH=win32
dr_
  • 4,746
7

To test and handle both the true and false the conditions on one line you can do this:

[ -f "/usr/bin/wine" ] && export WINEARCH=win32 || echo "No file"

You can include an exit code also:

[ -f "/usr/bin/wine" ] && export WINEARCH=win32 || exit 1

However, avoid including more than one command after the or operator because it will always be executed:

# This will always return an exit status of 1 even if the first condition is true
[ -f "/usr/bin/wine" ] && export WINEARCH=win32 || echo "No file" && exit 1
abk
  • 171
6

I also find that just typing any complex if then else command, hit enter, and then after it executes just hit the up arrow. The command line will repeat the last typed command of course but in this case it puts it all on one line as you require. It's a cheat way, but it's effective.

Alan
  • 61
3

If you need a little bit of more complexity, you may also use () to group statements and fine detail the operation:

[ -f "/usr/bin/wine" ] && (grep -Exiq /usr/bin/wine || echo "Foo" >> /usr/bin/wine)

In this case, it will not create the file /usr/bin/wine if it does not exists previously, whereas not using () will create it.