linux 命令 in -s,使用read命令解析linux shell腳本中的du -s輸出

I'm trying to write a shell script to perform actions if a users home directory if over a certain size. Unfortionately when I try to use the read command to split up the du -s output I get 'command not found' since it tries to pass the number through to the shell, not into a variable like I want. Here's what I have so far for the script.

我正在嘗試編寫一個shell腳本來執行操作,如果用戶主目錄超過一定大小。不幸的是,當我嘗試使用read命令拆分du -s輸出時,我得到'命令not found',因為它試圖將數字傳遞給shell,而不是像我想要的那樣傳遞給變量。這是我到目前為止腳本的內容。

#!/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 output like the following:

我得到如下輸出:

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

where 3284972 is the size of the directory.

其中3284972是目錄的大小。

4 个解决方案

#1

I think you'll want something along the lines of

我想你會想要一些東西

#!/bin/bash

for i in *

do

j=`du -s "$i" | cut -f 1`

echo $i size is $j

done

Reading into another variable, read, and playing with that seems redundant.

讀入另一個變量,讀取和播放它似乎是多余的。

I believe a more elegant solution is Jonathan Leffler's second method (copy-pasted here)

我相信更優雅的解決方案是Jonathan Leffler的第二種方法(復制粘貼在這里)

#!/bin/bash

cd /home

du -s * |

while read size name

do

...

done

#2

There are at least two ways to do this:

至少有兩種方法可以做到這一點:

Method 1:

#!/bin/bash

cd /home

for i in `ls`

do

set -- `du -s $i`

size=$1

name=$2

...

done

Method 2:

#!/bin/bash

cd /home

du -s * |

while read size name

do

...

done

#3

It's understandable that's happening as that's what you're telling it to. Backticks mean: evaluate this string, run it as a command and give me the output.

這是可以理解的,正如你告訴它的那樣。反引號意味着:評估此字符串,將其作為命令運行並給我輸出。

Also, read name means read data in to the variable name.

此外,讀取名稱表示將數據讀入變量名稱。

Try:

echo $j | read k

Or even removing the previous line:

甚至刪除上一行:

du -s $i | read k

(Edit - Testing this properly, it works fine in ksh but not in bash for some reason. I think it might be something to do with subshells. Use the backticks and cut solution below if you're using bash.)

(編輯 - 正確測試,它在ksh中工作正常,但由於某種原因沒有在bash中工作。我認為它可能與子shell有關。如果你使用bash,請使用反引號和下面的解決方案。)

You could keep your backticks and use cut rather than read:

你可以保留你的反引號並使用剪切而不是閱讀:

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

In this case it probably doesn't give you much more, but cut is more powerful than read which might help you sometime in the future.

在這種情況下,它可能不會給你更多,但切割比讀取更強大,這可能在將來的某個時候幫助你。

#4

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

如果您只想限制用戶可以使用的磁盤空間量,您可能需要查看磁盤配額的概念。

Starting point: Quota @ LQWiki

起點:配額@LQWiki

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值