Reputation: 61
I am trying to get this bash script written in only one line. Mostly for fun's sake.
The script basically compiles a .c script if($1=0)
. And if($1=1)
, it checks to see if lifemp exists, if it does not, it compiles it, then runs lifemp with the 2nd - 5th
command line arguments.
Here is the working script with normal if statements:
#!/bin/bash
cd gol
if [ $1 -eq 0 ]; then
make clean
make lifemp USE_FILE=$2
elif [ $1 -eq 1 ]; then
if [ ! -f lifemp ]; then
make lifemp
fi
./lifemp $2 $3 $4 $5
fi
And here is what I have come up with for it only on one line.
If $1 = 0
, this runs fine. The problem comes when $1 = 1
.
I think it has something to do with me having a nested ternary expression to check if the lifemp file exists or not.
#!/bin/bash
cd gol && eval `[[ $1 = "1" ]] && (echo [[ ! -f lifemp ]] && (echo "make lifemp && ./lifemp $2 $3 $4 $5") || ("./lifemp $2 $3 $4 $5")) || (echo "make clean && make lifemp USE_FILE=$2")`
If anyone wants to rack their brain with me to try and figure it out, I would be very appreciative!
Thanks!
Upvotes: 0
Views: 3945
Reputation: 123550
Here, I pasted your if statement (minus indenting) into an interactive shell, and then hit up arrow which makes bash show it on one line:
if [ $1 -eq 0 ]; then make clean; make lifemp USE_FILE=$2; elif [ $1 -eq 1 ]; then if [ ! -f lifemp ]; then make lifemp; fi; ./lifemp $2 $3 $4 $5; fi
eval
is always a bad idea, especially with user supplied data. You will now be treating arguments as code rather than data, which will break in fun and exciting ways if any of them contain shell metacharacters, including spaces, apostrophes, dollar signs and glob characters.
Upvotes: 1
Reputation: 61
I finally figured it out!
Here is the line I came up with
cd gol && eval `[[ $1 = "1" ]] && ([[ ! -f lifemp ]] && (echo "make lifemp && ./lifemp $2 $3 $4 $5") || (echo "./lifemp $2 $3 $4 $5")) || (echo "make clean && make lifemp USE_FILE=$2")`
I basically changed the second ternary expression to get rid of the echo before the [[, and instead added an echo before the "./lifemp $2 $3 $4 $5".
Upvotes: 1