0

I want to write number to variable using following expression val=$(ls -al $1 | awk -v a=$i '{if( NR == a ) print $5}') but for every i it returns 0 in simmilar expresion it writes name of file without any problem

3
  • 1
    What similar expression? What is $1 and what is $i? Note that field 5 in the output of ls -l is a file size, not a filename.
    – Kusalananda
    Dec 9 '20 at 21:00
  • $1 is a arg passed to an script by user and $i is variablem from for loop in similar expression only diffrent section is print $9
    – Roxor0
    Dec 9 '20 at 21:05
  • 2
    Parsing the output from ls is unsafe and usually leads to problems. Doing so using a user-supplied pathname (unquoted), and an index variable (also unquoted) is very thin ice. Dec 9 '20 at 23:27
0

You seem to want to print 5th name in the current directory.

The correct way to do that is

shopt -s dotglob
set -- *
printf '%s\n' "$5"

This sets the positional parameters to the list resulting from expanding the * filename globbing pattern (including hidden names since we're also setting the dotglob shell option). The 5th positional parameter, $5, will hold the name that sorts lexicographically at position 5. If the directory holds less than five names, the above would print an empty line.

It does not matter whether the names contain spaces, tabs or newlines.

To assign the name to a variable, use

val=$5

Would you want to select the name from the contents of another directory than the current one, for example a directory $dir, then use "$dir"/* as the pattern.

Would you want the size of the file instead of the name, then use stat on it:

stat -c %s "$5"

or, to assign to a variable,

val=$( stat -c %s "$5" )

The above assumes GNU stat and will give you the file's size in bytes, assuming it exists.

If you want to use a named array instead of clobbering the positional parameters, then use e.g.

names=( "$dir"/* )

Then fetch the 5th name with "${names[4]}" (arrays start at index zero in the bash shell).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.