简体   繁体   English

创建一个使用cat并具有3个参数的简单bash脚本

[英]Creating a simple bash script that uses cat and has 3 arguments

I have this bash command I am using to cat the output of two java programs that take 1 parameter each into a file: 我有这个bash命令,用于对两个Java程序的输出进行分类,每个程序将1个参数放入一个文件中:

cat file.ext | java program1 argument1 | java program2 argument2 > argument3

argument3 is a optional and if it is not provided it should just be file.srtd arguments3是可选的,如果未提供,则应仅为file.srtd

How can I create a bash script for this? 如何为此创建bash脚本?

You can specify a default value for a variable if it's not set with the syntax ${var:-default} . 如果未使用语法${var:-default}设置变量,则可以为其指定默认值。

java program1 "$1" < file.ext | java program2 "$2" > "${3:-file.srtd}"

You should also remember to quote the variables in case they contain special characters. 您还应该记住用引号将变量包含特殊字符。

In bash, the variable $n is the n th argument. 在bash中,变量$n是第n 参数。 The variable $# is the number of arguments given by the user. 变量$#是用户给定的参数数量。

So you can do something like this: 因此,您可以执行以下操作:

#!/bin/bash

arg3=$3
if (( $# < 3 )) ; then
    arg3="file.srtd"
fi;

cat file.ext | java program1 $1 | java program2 $2 > $arg3

You can look at shell parameters and shell parameter expansion for more information. 您可以查看shell参数shell参数扩展以获取更多信息。

You could do : 你可以做:

file="$3"
[ -z "$file" ] && file="file.srtd"
#then use `file` for the rest of the program.

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

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