根据用户输入创建文件
问题描述:
我有一个bash脚本,要求用户输入3个数字(例如123)。根据用户输入创建文件
我被困在如何分开这些数字以创建file1,file2,file3,我也必须确定它们是否是唯一的。
任何帮助,将不胜感激。
如果需要,我可以发布我的bash脚本。
! /bin/bash
clear
echo -n "Enter three digits number: "
read number
echo $number | grep "^[0-9][0-9][0-9]$"
if [ "$?" -eq 1 ]
then
echo "Error!! Please enter only 3 numbers."
exit 1
fi
if [ -d ~/a2/numbers ]
then
rm -r ~/a2/numbers
fi
mkdir ~/a2/numbers
if [ ! -e ~/a2/products ]
then
echo "Error the file \'products\'! does not exist"
exit 1
fi
echo ' '
cat ~/a2/products
echo ' '
cut -f2 -d',' ~/a2/products > ~/a2/names
cat ~/a2/names
echo "I have $(cat ~/a2/names | wc -l) products in my product file"
echo ' '
答
您可以使用命令fold
这将分割你的字符串。例如:
echo ${number} | fold -w1
要检查,如果他们是唯一只使用if
语句,因为在你的情况,你只允许三个一数字。
答
#!/bin/bash
read -p "enter 3 numbers: " nums
if [[ $nums != [0-9][0-9][0-9] ]]; then
echo "digits only please"
exit
fi
read n1 n2 n3 < <(sed 's/./& /g' <<< $nums)
if ((n1 == n2)) || ((n1 == n3)) || ((n2 == n3)); then
echo "no duplicate numbers"
exit
fi
总是发表任何你有的代码。尝试发布最相关的部分,如果它很长。 – 2012-08-09 04:08:51
我意识到,我发布后,我应该有:(。我的坏。 – 2012-08-09 04:10:51
@crashez在一个侧面说明,bash可以做不带'grep'的正则表达式:'if [[$ number =〜^ [0-9] {3} $]];然后...' – jordanm 2012-08-09 05:20:57