Jeff82 Jeff82 - 5 months ago 11
Bash Question

Unable to get bash if condiftion to work with multiple commands per outcome

I have been trying to get various versions of this to work:

[[ -e "~/usersl" ]] && { user=`cat ~/usersl`; echo Username: $user; } || { read -p "Username:" user; echo $user > ~/usersl; }


The main goal is to have a if..then..else all in one line. From what I have read on this site and others, this should work. It should check to see if the usersl file exists and if it does then it prints out the detected username and populates the $user variable. If the usersl file doesn't exist then it should ask for the username and populate the variable at the same time then record the new username into a file. Once that has been done the next tiem the command is ran the file already exists and it just displays the username and propagates the variable. Hope my explanation isn't overly complicated but the task is very simple.

Any help is much appreciated

Answer

Your most immediate bug had nothing to do with the conditional syntax, but was caused by a bug in how you were quoting around your test:

if [[ -e ~/usersl ]]; then
  user=$(<~/usersl)
  echo "Username: $user"
else
  read -p "Username:" user
  echo "$user" > ~/usersl
fi

As a one-liner, this would be:

if [[ -e ~/usersl ]]; then user=$(<~/usersl); echo "Username: $user"; else read -p "Username:" user; echo "$user" >~/usersl; fi

  • Tilde expansion is suppressed by quotes. If in doubt, write $HOME instead of ~.
  • Using a && b || c is bug-prone: If a succeeds and b tries to run but fails, you can have c run even though b was also invoked.