小编Ram*_*ddy的帖子

使用“source file.sh”、“./file.sh”、“sh file.sh”、“../file.sh”执行shell脚本有什么区别?

看看代码:

#!/bin/bash
read -p "Eneter 1 for UID and 2 for LOGNAME" choice
if [ $choice -eq 1 ]
then
        read -p "Enter UID:  " uid
        logname=`cat /etc/passwd | grep $uid | cut -f1 -d:`
else
        read -p "Enter Logname:  " logname
fi
not=`ps -au$logname | grep -c bash`
echo  "The number of terminals opened by $logname are $not"
Run Code Online (Sandbox Code Playgroud)

此代码用于查找用户在同一台​​ PC 上打开的终端数量。现在有两个用户登录,比如 x 和 y。我目前以 y 身份登录,用户 x 中打开了 3 个终端。如果我使用上面提到的不同方式在 y 中执行此代码,结果是:

$ ./file.sh
The number of terminals opened …
Run Code Online (Sandbox Code Playgroud)

command-line bash scripts

14
推荐指数
1
解决办法
7942
查看次数

shell 脚本中的区分大小写

考虑这个 Bash 脚本:

#!/bin/bash
echo Enter any character
read char
case $char in
    [a-z]) echo Lower case letter
            ;;
    [A-Z]) echo Upper case letter
            ;;
    [0-9]) echo Number
            ;;
    ?) echo Special char
            ;;
    *) echo You entered more than one character 
            ;;
esac
Run Code Online (Sandbox Code Playgroud)

如果我输入“a”,输出是小写字母,“A”也是一样的......我该如何克服这个问题?

bash scripts

10
推荐指数
2
解决办法
4836
查看次数

管道时如何抑制 tar 错误消息

例如:我使用 tar -xvf 而不是 tar -xjvf 提取 tar.bz2 文件:

 tar -xvf file.tar.bz2
 tar: invalid tar magic
Run Code Online (Sandbox Code Playgroud)

如果重定向标准错误

 tar -xvf file.tar.bz2 2>/dev/null
Run Code Online (Sandbox Code Playgroud)

有用。

现在如果我使用管道

 tar -xvf file.tar.bz2 | grep "something" 2>/dev/null 
 tar: invalid tar magic
Run Code Online (Sandbox Code Playgroud)

在这里,如果第一个命令失败,我将无法抑制错误。

有没有办法以这种方式压制

command-line tar

6
推荐指数
2
解决办法
8693
查看次数

如何逃避“。” 用 sed 还是 grep?

我有file

denm.xyz
denm.abc
denm.def
denm_xyz
denm_abc
denm_def
Run Code Online (Sandbox Code Playgroud)

我想提取其中的那些.

我试过

grep "denm\.*" file
grep 'denm\.*' file

sed "/denm\.*/p" file
sed '/denm\.*/p' file
Run Code Online (Sandbox Code Playgroud)

这些东西与世界上的一切相匹配 file

然而使用 awk

awk '/denm\./' file 
Run Code Online (Sandbox Code Playgroud)

工作了!!

我如何使用grep或做同样的事情sed

command-line bash grep sed

6
推荐指数
2
解决办法
2917
查看次数

tee 命令有什么问题?

我正在运行以下python脚本pipedtee命令

#!/usr/bin/python

from sys import exit,exc_info
from time import sleep

try:
    print "hello"
    #raise KeyboardInterrupt
    while True:
        print "hello"
        sleep(1)

except KeyboardInterrupt:
    print "Key board Interrupt"
    exit(0)
Run Code Online (Sandbox Code Playgroud)

假设我将其存储在file.py

现在如果我执行:

./file.py | tee somefile
Run Code Online (Sandbox Code Playgroud)

现在按Ctrl+C,观察没有任何内容打印到somefilestdout

正常执行情况下:

./file.py
Run Code Online (Sandbox Code Playgroud)

之上Ctrl+C

 hello
 hello
 ^CKey board Interrupt
Run Code Online (Sandbox Code Playgroud)

文件重定向也工作正常。出了什么问题tee

python command-line bash

2
推荐指数
1
解决办法
3864
查看次数

标签 统计

bash ×4

command-line ×4

scripts ×2

grep ×1

python ×1

sed ×1

tar ×1