Using the read command to parse du-s output in linux shell script

I am trying to write a shell script to perform actions in the users home directory if it has a specific size. Unfortunately, when I try to use the read command to separate the output du -s, I get the "not found" command, because it tries to pass the number to the shell, and not to the variable as I want. Here is what I have done so far for the script.

#!/bin/bash
cd /home
for i in `ls`
do
    j=`du -s $i`
    #this line gives me the error
    k=`$j |read first;`
done

I get the output as follows:

./takehome.sh: line 6: 3284972: command not found

where 3284972 is the size of the directory.

+3
source share
4 answers

I think you want something like strings

#!/bin/bash
for i in *
do
    j=`du -s "$i" | cut -f 1`
    echo $i size is $j
done

Reading into another variable, reading and playing back with this seems redundant.

, ( )

#!/bin/bash
cd /home
du -s * |
while read size name
do
    ...
done
+7

:

1:

#!/bin/bash
cd /home
for i in `ls`
do
    set -- `du -s $i`
    size=$1
    name=$2
    ...
done

2:

#!/bin/bash
cd /home
du -s * |
while read size name
do
    ...
done
+7

, , . Backticks : , .

, read name name.

Try:

echo $j | read k

:

du -s $i | read k

(). , ksh, bash - . , . cut , bash.)

cut, read:

k=`$du -s $i | cut -f1`

, , , cut , read, - .

+2
source

If you just want to limit the amount of disk space that users can use, you can check out the concept of disk quotas.

Starting point: Quota @LQWiki

0
source

Source: https://habr.com/ru/post/1704342/


All Articles