linux - 将输出重定向到文件 shell 脚本

标签 linux bash shell ubuntu

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

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

最佳答案

评论很少:

  • 可以使用-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"

关于linux - 将输出重定向到文件 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663550/

相关文章:

java - 连接被拒绝错误 Java/Linux

bash - 如何在 bash 中向文本文件中一行的所有条目添加常量

bash - bash shell 脚本中的负数

Linux:在脚本中运行二进制文件

c - recv() 错误 C/C++ 套接字编程

Python 非阻塞读取命令

regex - 使用用户指定的替换字符串进行 sed 替换

regex - Find 命令中的正则表达式

java - 检查进程是否正在运行 linux shell 不工作

linux - 打开 zip 文件时出错或缺少 : jrebel. jar 的 JAR list