Can I specify redirects and pipes in variables?

I have a bash script that creates a Subversion patch file for the current directory. I want to change it for the zip of the created file if -z given as a script argument.

Here's the relevant part:

 zipped='' zipcommand='>' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip >' fi echo "Creating ${zipped}patch file $filename..." svn diff $zipcommand $filename 

This does not work because it passes | or > contained in $zipcommand as the svn argument.

I can easily get around this, but the question is whether these types of operators can ever be used when they are contained in variables.

Thanks!

+4
source share
4 answers

I would do something like this (use bash -c or eval):

 zipped='' zipcommand='>' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip -@ ' fi echo "Creating ${zipped}patch file $filename..." eval "svn diff $zipcommand $filename" # this also works: # bash -c "svn diff $zipcommand $filename" 

This works, but my version of zip (Mac OS X) required me to change the line:

 zipcommand='| zip -@ ' 

to

 zipcommand='| zip - - >' 

Edit: added @DanielBungert clause to use eval

+5
source

eval is what you are looking for.

 # eval 'printf "foo\nbar" | grep bar' bar 

Be careful with quotation marks on this.

+2
source

Or you should try zsh shell whic, which allows you to define global aliases, for example:

 alias -g L='| less' alias -g S='| sort' alias -g U='| uniq -c' 

Then use this command (which is somewhat mysterious for those who looked from behind ;-))

 ./somecommand.sh SUL 

NTN

0
source

Open a new file descriptor either in the process substitution to handle compression, or in the specified file. Then redirect the output of svn diff to this file descriptor.

 if [ "$1" = "-z" ]; then zipped='zipped ' filename=$filename.zip exec 3> >(zip > "$filename") else exec 3> "$filename" fi echo "Creating ${zipped}patch file $filename" svn diff >&3 
0
source

Source: https://habr.com/ru/post/1277124/


All Articles