bash脚本语法比较字符串为整数 [英] bash script syntax to compare strings as integers

查看:166
本文介绍了bash脚本语法比较字符串为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,我试图通过目录,运行到线的末端,例如,如果我有4个目录一排它会往下走/ D1 / D2 / D3 / D4,直到它找到文件或其他目录。如果D3有一个文件,它会停在那里。我被行LS计数打印到文件这样做的,如果有1目录的cd命令使用该名称。
我的文件是:

I have a bash script I am trying to run through directories to the end of the line, for example if I have 4 directories in a row it will go down /d1/d2/d3/d4 until it finds files or other directories. If d3 has a file, it will stop there. I was doing this by counting the lines ls prints to a file and if there's 1 directory use that name in a cd command. My file is:

`

#!/bin/bash


COUNTFILE="/home/username/fake.txt"

ITEMCOUNT=$(ls | wc -l)
echo "ITEMCOUNT" $ITEMCOUNT

echo $*

ONE="1"
echo "one" $ONE

if [["$ITEMCOUNT" -eq "$ONE"]]; 
then
  DIRCOUNT=$(find . -maxdepth 1 -type d | wc -l)
  echo "dircount" $DIRCOUNT
else
  DIRCOUNT="0"
fi


if [$DIRCOUNT == "1"]; then
  ls > $COUNTFILE
  PATH=$(head -1 $COUNTFILE)
  cd ./$PATH
fi

`

正如我得到

pipetester.sh: line 15: [[1: command not found
pipetester.sh: line 2

4:0:命令未找到

4: [0: command not found

我检查语法2小时,但它似乎是在抱怨我的如果行,为什么?

I checked syntax for 2 hours, but it seems to be complaining about my "if" lines, why?

推荐答案

把周围的命令名称空间,如 [ [

Put spaces around command names like [[ and [.

例如:

if [[ "$ITEMCOUNT" -eq "$ONE" ]]
then

或者,如果你喜欢分号:

or, if you like semicolons:

if [[ "$ITEMCOUNT" -eq "$ONE" ]]; then

if [ $DIRCOUNT == "1" ]; then

或(更好地利用引号):

or (better use of quotes):

if [ "$DIRCOUNT" == "1" ]; then  # Or just 1 (no quotes around it)

由于这些是命令,你需要周围的前pression过的部件空间(因为你有他们的话)。不要在shell脚本吝啬空间(也不要使用他们,他们是不允许的,如围绕在一个变量赋值 = )。

Because these are commands, you need spaces around the components of the expression too (as you have them already). Don't skimp on spaces in shell scripts (but also don't use them where they are not allowed, such as around the = in a variable assignment).

请注意,无论是 [命令和 == 运算符[都是Bash扩展相比POSIX 外壳

Note that both the [[ command and the == operator for [ are Bash extensions compared to the POSIX shell.

这篇关于bash脚本语法比较字符串为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆