Bash if on single line

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.

3

3 Answers

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
4

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.

1

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like