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