gpt4 book ai didi

Bash 脚本 - 从文件中添加/减去 1

转载 作者:行者123 更新时间:2023-12-04 18:37:48 31 4
gpt4 key购买 nike

这就是我想要做的:

我想做一个脚本,我可以用 counter_use in 调用。或 counter_use out .如果我输入 in如果我键入 out,我希望计数器将 +1 添加到名为“计数器”的文件中的数值我想从文件中减去 1。

我还希望脚本输出 Logged in如果 counter 中的值等于或大于 1 并且 Not logged in如果计数器等于 0。

如果我将计数器硬编码为特定数字,则最后一部分将运行。问题是第一部分。

echo "In or out?"

read input > counterFile

if grep -q "in" counterFile
then //what should I do here so that it adds +1 to a file called
counter?

elif grep -q "out" counterFile
then //what should I do here so that it subtracts -1 to a file called
counter?

if [ $counter -ge 1 ]
then
echo "Logged in"

elif [ $counter -eq 0 ]
then
echo "Not logged in"

else
echo "Wrong input"

fi

最佳答案

romaric crailox's helpful answer包含许多有用的指针,但可以简化代码以成为更惯用的(Bash)解决方案:

#!/bin/bash

# Create the counter file on demand.
[[ -f counter ]] || echo 0 > counter

# Prompt until valid input is received.
while read -p 'In or out? ' input; do

case $input in
'in')
# Update the counter file by incrementing the number it contains.
perl -i -ple '++$_' counter
break # valid input received, exit the loop
;;
'out')
# Update the counter file by decrementing the number it contains.
perl -i -ple '--$_' counter
break # valid input received, exit the loop
;;
*)
echo "Invalid input." >&2 # echo error to *stderr*
# Stay in the loop to prompt again.
;;
esac

done

# Read the updated counter file and echo the implied status.
counter=$(< counter)
if (( counter >= 1 )); then
echo 'Logged in.'
elif (( counter == 0 )); then
echo 'Not logged in.'
else
echo "Invalid state: counter is $counter" >&2
fi

笔记:
  • 使用case ... esacif ... elif ... fi 更简洁地处理多个条件陈述。
  • 使用 >&2 将错误消息输出到 stderr
  • 使用 perl更新文件的命令 counter到位:
  • -i激活就地更新
  • -ple自动p冲洗(修改的)输入行,-l增加了智能换行处理和-e指定 e xpression(脚本)运行(以下参数)
  • ++$_/--$_然后简单地增加/减少手头的输入行( $_ ),这要归功于 -p , 自动获取输出,感谢 -i ,写回原始文件(松散地说;创建一个替换原始文件的新文件)。
  • 使用算术评估 ((( ... ))) 来测试数字。
  • 关于Bash 脚本 - 从文件中添加/减去 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43323587/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com