0

Hi just wondering about the use of && and { } in this example down below, does it mean that if you use the && and follow by { you write a shell script without having to create one before hand? Thank you in advance

$ mkdir -p lpi103-7 && cd lpi103-7 && {
> echo -e "1 apple\n2 pear\n3 banana" > text1
> echo -e "9\tplum\n3\tbanana\n10\tapple" > text2
> echo "This is a sentence. " !#:* !#:1->text3
echo "This is a sentence. " "This is a sentence. " "This is a sentence. ">text3
> split -l 2 text1
> split -b 17 text2 y; 
> cp text1 text1.bkp
> mkdir -p backup
> cp text1 backup/text1.bkp.2
> }
2

The && notation is a boolean operator for AND, which means that it uses the result of the previous command and only executes the next command if the exit code from the first command is 0.

So this is a shorthand for:

ls a &> /dev/null && echo "Done"

this, which basically does the same thing.

ls a &> /dev/null
if [ $? = 0 ]; then
    echo "Done"
fi

the { is for grouping commands to run, so this:

ls a &> /dev/null && {
    echo "This will happen if"
    echo "ls command returns 0"
}

is a shorthand for this:

ls a &> /dev/null
if [ $? = 0 ]; then
    echo "This will happen if"
    echo "ls command returns 0"
fi

You can also do the same with the OR || operator so you get the else part of the if as well. Like this

ls a &> /dev/null && echo "Done" || echo "No can do!"

And also combine it with the grouping of commands:

ls a &> /dev/null && {
    echo "This will happen if"
    echo "ls command returns 0"
} || {
    echo "This will happen if"
    echo "ls command returns other than 0"
}
1

Scripts are files which contains many unix commands, you can either create a file containing your commands or write those commands in Terminal directly in {} .

&& is used for executing the other command after previous command.

In you example,

mkdir -p lpi103-7

creates a directory with name lpi103-7

and

cd lpi103-7

is used to change current directory to lpi103-7

when you use

&&

it executes mkdir command followed by cd command

1

&& operator executes the statement to the right only if the one to the left succeeded. So mkdir -p lpi103-7 (create lpi103-7 directory) comes first, if successfully executed, we go to cd lpi103-7 (go to that directory) , and if that is successful, we will go to the next block of statements

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.