通过linux脚本将输出写入文件?

时间:2015-06-08 03:29:06

标签: linux input scripting

我必须在linux中编写一个脚本,将一行文本保存到文件中,然后添加一个新行。我现在拥有的是:

read "This line will be saved to text." Text1
$Text1 > $Script.txt
read "This line will be appended to text." Text2
$Text2 >> $Script.txt

2 个答案:

答案 0 :(得分:0)

脚本编制的一个主要好处是可以自动化流程。运用 read就像你摧毁了那个。您可以接受来自用户的输入 失去自动化:

#!/bin/sh
if [ "$#" != 3 ]
then
  echo 'script.sh [Text1] [Text2] [Script]'
  exit
fi
printf '%s\n' "$1" "$2" > "$3"

答案 1 :(得分:0)

假设您不介意每次运行脚本时是否覆盖(不附加)输出文件的第二行;这可能会。

#!/bin/sh
output_file=output.dat
if [ -z "$1" ] || [ -z "$2" ]; then echo Need at least two arguments.; fi
line1=$1; line2=$2
echo $line1 > $output_file
echo $line2 >> $output_file

执行脚本:

# chmod +x foo.sh 
# ./foo.sh 
Need at least two arguments.
# ./foo.sh hello world
# cat output.dat 
hello
world