【问题标题】:Redirecting output to file shell script将输出重定向到文件 shell 脚本
【发布时间】:2017-04-27 16:43:35
【问题描述】:

我正在尝试制作一个脚本,该脚本将接受用户的输入(名称和用户名),然后将该输入定向到以该用户名命名的文本文件。我在下面的代码将创建文件,但不会将任何数据定向到文件中。 有人可以帮我解决这个问题吗?谢谢

echo "What is your name?"
read name
echo "What is your chosen username?"
read username
cd user_records
$name >> "$username".txt
$username >> "$username".txt

【问题讨论】:

  • 添加echo...echo $name >>...

标签: linux bash shell ubuntu


【解决方案1】:

几个cmets:

  • 可以使用-p参数读取。
  • 除非您知道为什么不想要它,否则请始终使用 -r
  • 您应该检查cd 是否成功 - 如果不成功怎么办?
  • 总是引用你的变量
#!/bin/bash
err(){ echo "$@" >&2; return 1; }

udir="./user_records"

read -r -p  'What is your name?> ' name
read -r -p  'What is your chosen username?> ' username
cd "$udir" || err "Can't cd to $udir" || exit 1
printf "%s\n%s\n" "$name" "$username" >> "$username.txt"

或者你可能不需要cd,在这种情况下你可以写

err(){ echo "$@" >&2; return 1; }

udir="./user_records"

read -r -p  'What is your name?> ' name
read -r -p  'What is your chosen username?> ' username
[[ -d "$udir" ]] || err "The $udir doesn't exists" || exit 1
printf "%s\n%s\n" "$name" "$username" >> "$udir/$username.txt"

【讨论】:

  • 干杯,我试试看!
  • 是的,我有很多其他的东西,但删除了它——感觉就像被问到的东西过分了。我不知道。
  • 顺便说一句,我的标准 cd 错误检查是 cd dir || { echo "error" >&2; exit 40; } 串两个 ||不需要。另外,你可以做read -rp "this is my prompt: " 并节省一些空间:-)
  • @jm666 你错过了我的意思。我实际上有一个函数库,它有一个 log() 和 err(),它还用日期/时间字符串在字符串前面。我的意思是您正在执行两个 OR 命令,而不是将错误消息包装在大括号中并退出。
【解决方案2】:

Lohmar 给出了答案,但您需要回显变量。您的代码正在尝试执行 $name 和 $username,但您需要将其用作数据,而不是命令。

echo -n "What is your name? "
read name
echo -n "What is your chosen username? "
read username
cd user_records
echo "$name" >> "$username".txt
echo "$username" >> "$username".txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多