0

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!

1
  • bash doesn't have a ternary operator. The precedence of a chain of && and || operators is not quite the same as in C; a && b || c will run b only if a succeeds, but a succeeds and b subsequently fails, c will run as well. Commented Feb 20, 2014 at 14:09

2 Answers 2

1

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".

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.