Home > Net >  Confused about special character $ in a bash script
Confused about special character $ in a bash script

Time:08-10

I'm a beginner trying to learn bash script and I came across this snippet of a reference code and have no clue what it means because of all the $. Can anyone explain this to me?

    for i in $(seq $1 1 $2)
    do
    mkdir /for/july23/$$_$i
        cd $i
    origin=$PWD

CodePudding user response:

Let's start with the first expression $(seq $1 1 $2), it runs the command seq in a subshell with the $() syntax.

If you type man seq on your terminal you get the following information:

NAME
       seq - print a sequence of numbers

SYNOPSIS
       seq [OPTION]... LAST
       seq [OPTION]... FIRST LAST
       seq [OPTION]... FIRST INCREMENT LAST

So seq when used with three arguments, generates numbers from FIRSTto LAST, with an offset equal to INCREMENTS. So if you do seq 1 2 10, you'll get the sequence 1 3 5 7 9. Since in your code the increment is 1, it could be replaced by seq $1 $2, which would yield the same values, since the default increment is already 1.

Now for the line mkdir /for/july23/$$_$i, here you have two variables used to create a directory, the first $$ is the unique process id pid, and the other, $i is the current number in the sequence inside your for loop.

The line with cd $i changes the directory with that name, it fails if the directory $i does not exist.

And lastly, origin=$PWDassigns the value of a variable called PWD to a new one called origin. In bash, the command pwd refers to the current directory, so that is probably what the value of PWD is.

CodePudding user response:

The $(seq $1 1 $2) introduces command substitution. It is replaced with the output of the command itself.

The $1, $2, $i, $$ and $PWD introduces parameter expansion. It is replaced with the value of the parameter.

So the code loop through each number on the output of seq $1 1 $2, creates the directory /for/july23/$$_$i, changes the working directory to $i and set the value of parameter origin to $PWD.

  • Related