JohnnyF
JohnnyF

Reputation: 1101

Error in bash script - assign value to variable

I am trying to make a small script that will give me the File names without the $2 first and $3 last names in a $1 directory

I have this code

#!/bin/bash
TOTFILES=find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l
find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort |
    head -n (( TOTFILES-$3 )) | tail -n (( TOTFILES-$3-$2 ))

My main problem is that I can't assign TOTFILES with the output of that long line.

I think if I can get that value assigned, it will work (hopefully) :)

PS: I don't know if I used

(( TOTFILES-$3 ))

right, to get the value.

Thanks for the fast answer. Now I get a new problem; I guess (( )) is not the right way to get number

./middleFiles: line 5: syntax error near unexpected token `('
./middleFiles: line 5: `find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort | head -n (( TOTFILES-$3 ))  | tail -n (( TOTFILES-$3-$2 ))'

Upvotes: 2

Views: 237

Answers (3)

armnotstrong
armnotstrong

Reputation: 9065

I think best way is to assign filenames to an array. According to your code, you just want depth = 1 so simple ls trick will do the job

#!/bin/bash

TOTFILES=($(ls -p $1 | grep -v / | sort -n)

# and you can use the array like this
for file in ${TOTFILES[*]};do 
    echo $file;
done
# leave you to get a subset of the ${ToTFILES}
# refer to http://stackoverflow.com/questions/1335815/how-to-slice-an-array-in-bash

Upvotes: -2

johnsyweb
johnsyweb

Reputation: 141770

Command substitution assigns the output of a command:

TOTFILES=$(find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l)

Arithmetic expansion will get you the argument to head and tail:

head -n $(( $TOTFILES - $3 ))

Upvotes: 3

abelenky
abelenky

Reputation: 64672

I believe you need backticks around the expression you want evaluated.

TOTFILES=`find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l`

See this answer for details.

Upvotes: 0

Related Questions