4LegsDrivenCat
4LegsDrivenCat

Reputation: 1361

Using escape character to combine commands in shell?

I've seen strange usage of escape character in a bash script (the line with unzip):

#!/usr/bin/env bash
echo "doing something"
unzip "${1}" || echo "Failed to unzip ${1}" \ exit 1
echo "doing something"

Escaping a space to combine commands? Is unzip line equivalent to the following?

unzip "${1}" || (echo "Failed to unzip ${1}"; exit 1)

How does it work?

Upvotes: 1

Views: 86

Answers (1)

Inian
Inian

Reputation: 85560

The \ is one way to preserve literal value of the character following it. See Bash manual - 3.1.2.1 Escape Character

So in your case, the \ just escapes the space character. So basically, the exit 1 is not run, but just concatenated as literal arguments to echo along with expanded value of "Failed to unzip ${1}" i.e.

echo 'Failed to unzip ' ' exit' 1

But the below case, runs the actual exit 1 returning a exit code back to the parent shell after echoing the error from unzip because of the command grouping, where each command in the group (..) separated by ; are executed.

So the examples are not the same.

(echo "Failed to unzip ${1}"; exit 1)

A minimal example to recreate and understand the behavior is to do below and manually check the exit codes after running both i.e. doing echo $?

false || echo 'failure?' \ exit 1
failure?  exit 1

and

false || ( echo 'failure?';  exit 1 ; )
failure?

Upvotes: 2

Related Questions