Alexandre Thebaldi Alexandre Thebaldi - 8 months ago 43
Linux Question

How to share an argument with system calls on bash?

Actually I don't know much about bash programming. I've read that pipes allows we to use the output of a program as the input of another one. Then I expected that some expression like bellow to works:

echo "newdirectory" | (mkdir && cd)

receives the outputed string from
as it first argument and after
too. The other point is that pipes not executes synchronously from left processes to the right (is that?).

There is a way to reuse an argument through the system calls on bash?

Especially in this case of creating a new directory and change to it.

nos nos

You can use variables for this, and pass command line arguments to the the two commands mkdir and cd, instead of trying to pipe data to these commands.

mkdir "$MYDIR" && cd "$MYDIR"

With this,

echo "newdirectory" | (mkdir && cd)

You connect standard input of both mkdir and cd. A program/command need to know if it should read data from stdin, and what to do about it. Neither the mkdir or cd command does this, they expect you to give them command line arguments.

Even in the case the commands could read data from standard input, in this case mkdir would consume the input, and not leave anything for cd. In other cases where you connect the same pipe to several commands/processes, you cannot determine which one of them would read the data.

Moreover the parenthesis in (mkdir && cd) means that the commands are run in a sub-shell. However cd affects only the current shell, so you would not be able to observe any effect of the cd command.