我尝试创建一个脚本,该脚本将从用户那里获取输入(名称和用户名),然后将该输入定向到使用该用户名命名的文本文件。我下面的代码将创建文件,但不会将任何数据导入文件。 任何人都可以帮我解决这个问题吗?感谢
echo "What is your name?"
read name
echo "What is your chosen username?"
read username
cd user_records
$name >> "$username".txt
$username >> "$username".txt
答案 0 :(得分:3)
很少有评论:
-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"
答案 1 :(得分:0)
Lohmar给出了答案,但你需要回应变量。您的代码正在尝试执行$ name和$ username,但您需要将其用作数据,而不是命令。
"${array[$idx]}"