我是 bash 脚本新手,正在尝试制作脚本
目标:接收 2 个名称(1 - 日志文件名 2- 程序名称)程序应该编译该程序
并将两个输出发送到日志
如果成功则写入“compile V”并返回0,否则编译X并返回数字
我试过了
#!/bin/bash
gcc {$2}.c -Wall -g -o $2> $1 2>&1
exit
我不知道如何检查它是否成功以及如何回显 V 或 X
编辑: 谢谢你们,我明白了
#!/bin/bash
gcc {$2}.c -Wall -g -o ${2}>${1} 2>&1
if (($?==0));then
echo Compile V
[else
echo compile X]
fi
exit
但是所有的 if 部分仍然无法工作...
您可以像这样检查退出状态
gcc
:
#!/bin/bash
# execute gcc command
gcc "$2".c -Wall -g -o "$2"> "$1" 2>&1
# grab exit status of gcc
ret=$?
# write appropriate message as per return status value
((ret == 0)) && echo "compile V" || echo "compile X"
# return the exit status of gcc
exit $ret
您可以通过命令
$?
在bash中检查程序是否成功,如果echo $?
= 0则成功,否则失败。
这段代码应该可以工作:
#!/bin/bash
gcc -v ${2}.c -Wall -g -o ${2}>${1} 2>&1
exit
试试这个:
#!/bin/bash
gcc "$2"".c" -Wall -g -o "$2" 2>&1 >"$1"
#check for error of previous command
if $? ; then echo compile V >>"$1"
else echo compile X >>"$1"; fi
exit
这是我的解决方案:
#!/bin/bash
rm -- "$0"
#1 这也是我的解决方案:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Error: No arguments provided. Please provide at least one number."
exit 1
fi
sum=0
for arg in "$@"; do
sum=$((sum + arg))
done
echo $sum
#2 这也是一个可能的解决方案
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <input_file>"
exit 1
fi
input_file="$1"
wget {link_here}
while IFS= read -r word; do
if grep -q "\<$word\>" usr/share/dict/british-english; then
echo "$word in dictionary"
else
echo "$word not in dictionary"
fi
done < "$input_file"
rm wbritish_*.deb
rm -rf usr
#3