簡體   English   中英

這個shell腳本有什么錯誤

[英]What is the error in this shell script

我從未使用過shell腳本,但是現在我必須這樣做,這是我想要做的事情:

#!/bin/bash
echo running the program 
./first 
var = ($(ls FODLDER |wc -l))    #check how many files the folder contains 
echo $var
if( ["$var" -gt "2"] #check if  there are more the 2file 
then ./second 
fi

scriopt在if語句時崩潰。 我該如何解決

許多:

var = ($(ls FODLDER |wc -l))

這是錯誤的,您不能在=周圍留空格。

if( ["$var" -gt "2"]

您的(在那里沒有做任何事情,因此必須將其刪除。而且, []周圍需要空格。

總之,這將更有意義:

#!/bin/bash
echo "running the program"
./first 
var=$(find FOLDER -maxdepth 1 -type f|wc -l) # better find than ls
echo "$var"
if [ "$var" -gt "2" ]; then
    ./second 
fi

注意:

  • echo時引用,特別是在處理變量時。
  • 查看在給定路徑中查找文件的另一種方法。 解析ls是一種邪惡
  • 縮進代碼以提高可讀性。

如下編輯您的script.bash文件:

#!/bin/env bash
dir="$1"

echo "running the program"
./first 
dir_list=( $dir/* )    # list files in directory
echo ${#dir_list[@]}     # count files in array
if (( ${#dir_list[@]} > 2 )); then # test how many files
  ./second 
fi

用法

script.bash /tmp/

講解

您需要學習bash以避免危險的動作!

  1. 將目錄作為第一個參數傳遞給命令行( /tmp/ →`$ 1)
  2. 使用glob創建一個包含給定目錄中所有文件的數組( dir_list
  3. 計算數組中的項目( ${#dir_list[@]}
  4. 使用算術上下文測試項目的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM