The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

If you can read me, I'm broken!

Views: 25,803β€…    Votes:  4β€…
Tags: command-line   bash   scripts  
Link: πŸ” See Original Answer on Ask Ubuntu ⧉ πŸ”—

URL: https://askubuntu.com/q/1182804
Title: Why combine commands on a single line in a Bash script?
ID: /2019/10/21/Why-combine-commands-on-a-single-line-in-a-Bash-script_
Created: October 21, 2019    Edited:  October 23, 2019
Upload: December 22, 2024    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false


Why we sometimes like to use it

When we are writing answers here in Ask Ubuntu it is helpful to put them into one line which people can cut and paste into their terminal easier. For example:

$ CurrDir=$PWD ; cd /bin ; ls -la dd ; cd "$CurrDir"

-rwxr-xr-x 1 root root 72632 Mar  2  2017 dd

As mentioned earlier you could use && for the same effect but if there were errors above you could end up on the wrong directory. In this case ; is preferable to && that isn’t tested for success:

rick@alien:~/askubuntu$ CurrDir=$PWD && cd /bin && llllssss -la dd && cd "$CurrDir"

llllssss: command not found

rick@alien:/bin$ 

Why we have to use it

There are some commands where you have to string multiple lines together. One case is the abbreviated if-commands-fi which must be one line. For example:

$ [[ 2 -eq 2 ]] && { echo 2 equals 2 ; echo setting three to 3 ; three=3 ; }

2 equals 2
setting three to 3
⇧ Selected Sound Output Device Not Persisting Between Reboots in gnome-control-center What does >&2 mean in a shell script?  β‡©