Engine
Engine

Reputation: 5420

What is the error in this shell script

I never used shell script, but now I have to , here is what I'm trying to do :

#!/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

the scriopt crashes at the if statement. how may I solve this

Upvotes: 0

Views: 61

Answers (2)

Édouard Lopez
Édouard Lopez

Reputation: 43391

Edit your script.bash file as follow:

#!/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

Usage

script.bash /tmp/

Explaination

You need to learn bash to avoid dangerous actions!

  1. pass the directory to work with as first argument in the command line (/tmp/ → `$1)
  2. use glob to create an array (dir_list) containing all file in given directory
  3. count items in array (${#dir_list[@]})
  4. test the number of item using arithmetic context.

Upvotes: 2

fedorqui
fedorqui

Reputation: 289495

Many:

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

This is wrong, you cannot have those spaces around =.

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

Your ( is not doing anything there, so it has to be deleted. Also, you need spaces around [ and ].

All together, this would make more sense:

#!/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

Note:

  • quote whenever you echo, specially when handling variables.
  • see another way to look for files in a given path. Parsing ls is kind of evil.
  • indent your code for better readibility.

Upvotes: 5

Related Questions