Amumu
Amumu

Reputation: 18572

Groups of commands in Linux shell

Suppose I have this shell script call cpdir:

(cd $1 ; tar -cf - . ) | (cd $2 ; tar -xvf - )

When I ran it, the main shell should create two processes (subshells) to execute both groups of commands concurrently. However, how can the shell make sure that both processes change to appropriate directories, then first process package the content of the directory and send to the second process for unpacking?

Why is there no race condition? Is it a rule that every command of every process will execute in order, although processes can be parallel?

i.e. first process will run "cd $1", and then second process will run "cd $2" (or it should be execute the same time as the first process? Not sure), then first process will package everything and finally send to second process.

Although, one little thing I don't know about tar:

tar -cf - .

I know the dot (.) is the content of current directory. However, what's the '-' in the command?

Upvotes: 2

Views: 1079

Answers (3)

glglgl
glglgl

Reputation: 91139

As those groups run in independent processes, it doesn't matter which cd command runs first: each process has its own working directory.

So changing working directory does not affect the respectively other process.

Upvotes: 1

dogbane
dogbane

Reputation: 274828

You don't need to use cd because tar has a -C option which tells it to change to a directory. So you can simply use a command such as:

tar -C $1 -cvf - . | tar -C $2 -xvf -

- means stdin/stdout. The first hyphen tells tar to write to stdout. The second one tells tar to read from stdin.

Since - is the default, you don't even need to specify it. You can shorten your command to:

tar -C $1 -c . | tar -C $2 -x

Upvotes: 4

You are piping the commands in your case. The result you expect is not very clear to me. By the way, my GNU tar has no "-" value for this "-f" option. So you commands might be not portable.

Upvotes: 0

Related Questions