我想在变量中存储bash字符串比较的结果,效果等同于:
if [[ $a == $b ]]; then
res=1
else
res=0
fi
我希望能够写一些更简洁的东西,比如:
res2=$('$a'=='$b') #Not valid bash
有没有办法实现我想要的,而不是推迟if构造?
答案 0 :(得分:13)
我建议:
res=0; [ "$a" == "$b" ] && res=1
或
res=1; [ "$a" == "$b" ] || res=0
并不像您希望的那样简单,但确实避免使用if ... else ... fi
。
答案 1 :(得分:2)
您还可以使用包含上一个命令的返回值的$?
变量:
res="$( [[ $a == $b ]]; echo $? )"
虽然这会反转你给出的数字。最终结果将与:
相同if [[ $a == $b ]]; then
res=0
else
res=1
fi
这是因为shell将0
的返回值解释为true,将1
解释为false。
不是说我完全提倡这个解决方案。这是hackish,有点不清楚。但是你要求的是简洁和简洁。
答案 2 :(得分:0)
这是另一种选择。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="application/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script type="application/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.0.0-beta.9/vuetify.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.0.0-beta.9/vuetify.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons">
</head>
<body>
<div id="App">
<v-app id="inspire">
<v-app-bar
app
clipped-right
dark
>
<v-toolbar-title>Sample</v-toolbar-title>
<v-spacer></v-spacer>
</v-app-bar>
<v-content>
<v-container justify-center align-start>
<v-layout row >
<v-flex xs6>
<v-card dark color="primary">
<v-text-field readonly
label="TextField1"
></v-text-field>
</v-card>
</v-flex>
<v-flex xs6>
<v-card dark color="primary">
<v-text-field readonly
label="TextField2"
></v-text-field>
</v-card>
</v-flex>
</v-layout>
<v-layout row >
<v-flex xs6>
<v-card dark color="red">
<v-btn rounded color="green" v-on:click="MyFunction" >Button1</v-btn>
</v-card>
</v-flex>
<v-flex xs6>
<v-card dark color="red">
<v-btn rounded color="green" v-on:click="MyFunction" >Button2</v-btn>
</v-card>
</v-flex>
</v-layout>
<v-layout row >
<v-flex xs6>
<v-card dark color="red">
<v-btn rounded color="green" v-on:click="MyFunction" >Button3</v-btn>
</v-card>
</v-flex>
<v-flex xs6>
<v-card dark color="primary">
<v-text-field readonly
label="TextField3"
></v-text-field>
</v-card>
</v-flex>
</v-layout>
<v-layout row >
<v-flex xs6>
<v-card dark color="primary">
<v-text-field readonly
label="TextField4"
></v-text-field>
</v-card>
</v-flex>
<v-flex xs6>
<v-card dark color="primary">
<v-text-field readonly
label="TextField5"
></v-text-field>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-content>
</v-app>
</div>
<script type="text/javascript">
const opts = {
theme: {
dark: true
}
};
const vuetify = new Vuetify(opts);
app = new Vue(
{
vuetify
}
).$mount('#App');
</script>
</body>
</html>