简体   繁体   English

使用三元表达式打击单行

[英]Bash one-liner using ternary expressions

I am trying to get this bash script written in only one line. 我试图让这个bash脚本只用一行编写。 Mostly for fun's sake. 主要是出于好玩的缘故。 The script basically compiles a .c script if($1=0) . 该脚本基本上编译一个.c脚本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. if($1=1) ,它会检查lifemp是否存在,如果不存在,则编译它,然后使用第2nd - 5th命令行参数运行lifemp。

Here is the working script with normal if statements: 这是带有正常if语句的工作脚本:

#!/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. 如果$1 = 0 ,则运行正常。 The problem comes when $1 = 1 . $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. 我认为它与我有一个嵌套的三元表达式来检查lifemp文件是否存在。

#!/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! 谢谢!

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". 我基本上改变了第二个三元表达式以摆脱[[,而是在“./lifemp $ 2 $ 3 $ 4 $ 5”之前添加回声)之前的回声。

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语句(减去缩进)粘贴到交互式shell中,然后点击向上箭头,使bash在一行显示:

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. eval总是一个坏主意,特别是对于用户提供的数据。 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. 现在,您将把参数视为代码而不是数据,如果它们中的任何一个包含空格元字符,包括空格,撇号,美元符号和全局字符,它将会破坏有趣和令人兴奋的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM