从用户那里读取内容的脚本
Script to read contents from the user
如何编写 shell 创建文件的脚本
echo "Enter the file you want to create"
read a
touch $a
并向创建的文件添加内容'a'
echo "Enter the contents to your $a file:"
cat > $a << 'EOF'
EOF
上面的方法不对,我哪里做错了?
您可以询问然后进行简单的回显:
echo "Enter the file you want to create"
read file
echo "Enter the contents to your $a file:"
read content
echo "$content" > "$file"
你快到了。这将执行您的要求:
echo "Enter the file you want to create"
read a
echo "Enter the contents to your $a file (press ctrl-D when done):"
cat >"$a"
讨论
touch $a
不需要触摸文件。不管怎样,cat
语句都会创建它。
此外,因为文件名可以包含空格,所以最好将任何包含文件名的 shell 变量放在双引号内。这样可以防止分词。
cat > $a << 'EOF'
EOF
构造 << 'EOF'
告诉 shell 从 此处文档 读取。如果您的 shell 脚本中有您想要用作输入的文本,这就是您所使用的。你不知道。您想要改为读取用户的输入。因此,以上两行可以简单地替换为 cat >"$a"
.
如何编写 shell 创建文件的脚本
echo "Enter the file you want to create"
read a
touch $a
并向创建的文件添加内容'a'
echo "Enter the contents to your $a file:"
cat > $a << 'EOF'
EOF
上面的方法不对,我哪里做错了?
您可以询问然后进行简单的回显:
echo "Enter the file you want to create"
read file
echo "Enter the contents to your $a file:"
read content
echo "$content" > "$file"
你快到了。这将执行您的要求:
echo "Enter the file you want to create"
read a
echo "Enter the contents to your $a file (press ctrl-D when done):"
cat >"$a"
讨论
touch $a
不需要触摸文件。不管怎样,cat
语句都会创建它。
此外,因为文件名可以包含空格,所以最好将任何包含文件名的 shell 变量放在双引号内。这样可以防止分词。
cat > $a << 'EOF'
EOF
构造 << 'EOF'
告诉 shell 从 此处文档 读取。如果您的 shell 脚本中有您想要用作输入的文本,这就是您所使用的。你不知道。您想要改为读取用户的输入。因此,以上两行可以简单地替换为 cat >"$a"
.