AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / unix / 问题

问题[shell-script](unix)

Martin Hope
XavierWood
Asked: 2025-04-30 17:30:23 +0800 CST

如何从文件中读取一行并将该行输出到文件

  • 7

像这样的文件:ExampleFile.txt

line1TextHere
line2TextHere
line3TextHere

我想从文件中逐行读取并将其输出到不同的文件,因此文本的每一行都会有一个文件。看起来像这样:

# cat file1.txt
line1TextHere

# cat file2.txt
line2TextHere

# cat file3.txt
line3TextHere

到目前为止我知道,如果我想从示例文件中读取第 2 行,我可以这样做

# awk 'NR==2 {print $0}' ExampleFile.txt

我想我应该用循环读取文件三次,然后将其输出到三个不同的文件,但我不知道该怎么做。我用的是 Debian。谢谢。

shell-script
  • 2 个回答
  • 210 Views
Martin Hope
einpoklum
Asked: 2025-04-27 17:08:57 +0800 CST

生成唯一文件名的惯用方法?

  • 10

我正在编写一个脚本,想在文件系统上创建一个临时文件,但它不在我的文件系统中,/tmp而是在其他地方,而且可能不是文件也不是目录(例如,可能是命名管道或符号链接)。关键在于,我必须自己创建它。现在,我想为我的临时文件使用一个唯一的文件名,这样以后调用该实用程序以及任何其他正在运行的代码时,就不会尝试使用相同的名称。

如果我只是在中创建一个临时文件或目录/tmp,我可以使用mktemp。但是 - 当我只想生成名称时我该怎么做?

shell-script
  • 6 个回答
  • 445 Views
Martin Hope
harry mckay
Asked: 2025-04-10 21:14:32 +0800 CST

如何在具有 seq for 循环的脚本中使用 pv

  • 5

我有一个脚本,其中有一个运行特定次数的 for 循环,我想知道是否可以在我的脚本中实现 pv 命令来添加进度条。

这是我的代码:

for i in $(seq 1 10000000); do
    echo "iteration ${i}"
    #rest of for loop
done

日志:

iteration 1
iteration 2
iteration 3
iteration 4
iteration 5
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
*and so on

如果有人能帮助我,我将不胜感激

编辑:我稍微改变了代码:

for i in $(seq 1 10000000); do
    echo "iteration ${i}" | pv -l
    #rest of for loop
done

它给了我这个输出:

1
1.00  0:00:00 [15.2k/s] [  <=>                                                                                                                             ]
2
1.00  0:00:00 [14.7k/s] [  <=>                                                                                                                             ]
3
1.00  0:00:00 [15.6k/s] [  <=>                                                                                                                             ]
4
1.00  0:00:00 [15.0k/s] [  <=>                                                                                                                             ]
5
1.00  0:00:00 [15.0k/s] [  <=>                                                                                                                             ]
6
1.00  0:00:00 [11.5k/s] [  <=>                                                                                                                             ]
7
1.00  0:00:00 [5.54k/s] [  <=>                                                                                                                             ]
8
1.00  0:00:00 [14.7k/s] [  <=>                                                                                                                             ]
9
1.00  0:00:00 [13.2k/s] [  <=>                                                                                                                             ]
10
1.00  0:00:00 [13.4k/s] [  <=>                                                                                                                             ]
shell-script
  • 2 个回答
  • 78 Views
Martin Hope
PrismaPixel Studios
Asked: 2025-03-25 09:19:45 +0800 CST

我的 bash 脚本一直告诉我目录不存在,但实际上它确实存在

  • 5

我有一个脚本,当我运行它时,它会返回

Directory not found: ~/Pictures/Wallpaper

脚本如下:

#!/bin/bash
# Check if the wallpaper directory exists
if [ ! -d "$WALLPAPER_DIR" ]; then
  echo "Directory not found: $WALLPAPER_DIR"
  exit 1
fi

# Get currently loaded wallpaper
CURRENT_WALL=$(hyprctl hyprpaper listloaded)

# Get a random wallpaper that is not the current one
IMAGE=$(find "$WALLPAPER_DIR" -type f ! -name "$(basename "$CURRENT_WALL")" | -iname "*.jpg" -o -iname "*.png" -o -iname "*.jpeg" | shuf -n 1)

# Verify that an image was found
if [ -z "$IMAGE" ]; then
  echo "No images found in $WALLPAPER_DIR"
  exit 1
fi

环境$WALLPAPER_DIR变量在我的 hyprland.conf 文件中配置,其值为我已验证的 ~/Pictures/Wallpaper。

我相当困惑为什么当变量和文件夹确实存在时它会返回 if 语句的否定结果。

shell-script
  • 1 个回答
  • 26 Views
Martin Hope
SheCodes
Asked: 2025-03-24 14:47:43 +0800 CST

在 Bash 脚本中传递长位置参数

  • 5

我想向脚本传递长参数,并参考此链接。我创建了这个 my_script:

#!/usr/bin/env bash
#
# Adapted from https://www.shellscript.sh/examples/getopt/
#
set -euo pipefail

user_type=unset
user_id=unset
country=unset
dev_env=unset
position_id=unset

usage(){
>&2 cat << EOF
Usage: $0]
   [ -a | --user_type input
   [ -b | --user_id input ]
   [ -c | --country input ] 
   [ -d | --dev_env input ]
   [ -e | --position_id input ]
EOF
exit 1
}

>&2 echo [$@] passed to script

args=$(getopt -a -o ha:b:c:d: --long help,user_type:,user_id:,country:,dev_env:,position_id: -- "$@")
if [[ $? -gt 0 ]]; then
  usage
fi

>&2 echo getopt creates [${args}]

eval set -- ${args}
while :
do
  case $1 in
    -a | --user_type)   user_type=$2    ; shift 2  ;;
    -b | --user_id)    user_id=$2     ; shift 2  ;;
    -h | --help)    usage      ; shift   ;;
    -c | --country)   country=$2   ; shift 2 ;;
    -d | --dev_env)   dev_env=$2   ; shift 2 ;;
    -e | --position_id) position_id=$2 ; shift 2 ;;
    # -- means the end of the arguments; drop this, and break out of the while loop
    --) shift; break ;;
    *) >&2 echo Unsupported option: $1
       usage ;;
  esac
done

if [[ $# -eq 0 ]]; then
  usage
fi

>&2 echo "user_type   : ${user_type}"
>&2 echo "user_id    : ${user_id} "
>&2 echo "country   : ${country}"
>&2 echo "dev_env   : ${dev_env}"
>&2 echo "position_id   : ${position_id}"
>&2 echo "$# parameter/s remaining: $@"
>&2 echo "Looping through remaining parameter/s:"
# set input field separator to keep quoted parameters together
# for example, "my input" will remain as one input
IFS=$'\n'
for param in $@; do
   >&2 echo -e "\t${param}"
done

echo "user ${user_type} with user id ${user_id} has been created with position_id $position_id"
exit 0

并在终端上尝试运行它:

bash test_bash --user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf

我收到的帮助信息如下:

[--user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf] passed to script
getopt creates [ --user_type 'abc' --user_id 'a1b2' --country 'aus' --dev_env 'uat' --position_id 'aFWf' --]
Usage: test_bash]
   [ -a | --user_type input
   [ -b | --user_id input ]
   [ -c | --country input ] 
   [ -d | --dev_env input ]
   [ -e | --position_id input ]

我尝试更新/更改一些东西,比如 args=getopt 和其他几个选项。但我的参数没有被脚本解析。提前感谢您的帮助。谢谢。

shell-script
  • 2 个回答
  • 92 Views
Martin Hope
hollowillow
Asked: 2025-03-19 06:09:04 +0800 CST

需要 shell 脚本帮助 - 多次处理相同选项

  • 6

所以我遇到了一点障碍,我的脚本中有一个选项,它调用一个函数,允许我指定一个文件/目录,然后我想将该输出解析为菜单工具(在本例中使用 dmenu)以选择哪个文件是我特别想要的,并继续在同一脚本中将该选择作为变量使用。如果只有一个文件或目录,这种方法可以正常工作,但我希望能够多次使用该选项,然后一次性将所有输出解析为 dmenu。这是一个片段

fileSelection () {
    if [ -d "${OPTARG}" ]; then find "${OPTARG}" -type f; fi;
    if [ -f "${OPTARG}" ]; then printf '%s\n' "${OPTARG}"; fi;
}

while getopts "f:" option; do
   case "${option}" in
       f) file="$(fileSelection|dmenu)";;
   esac
done

就像我说的,如果我这样做,这会有效:

myscript -f file

或者

myscript -f directory

但我希望也能做到这一点:

myscript -f file1 -f file2

问题是,由于该函数是连续调用的,我无法像那样将输出解析到 dmenu,因为它不使用选项 file1 和 file2 调用 dmenu,而是先使用 file1,然后使用 file2,我希望这有意义。

我可能遗漏了一些非常简单的解决方案,我曾考虑过将输出简单地写入文件,然后解析可能有效的文件,但如果可能的话,我想避免通过管道传输到文件。我也试图使其符合 POSIX 标准,并希望得到后续的答案。

shell-script
  • 4 个回答
  • 106 Views
Martin Hope
Arch Stanton
Asked: 2025-03-16 18:52:43 +0800 CST

程序用什么来读取它们的环境?

  • 7

我使用的是 Fedora,其中所有预装的 shell 显然都支持 bashism:bash --posix确实如此,甚至如此sh。不过,当我使用这个函数时,

pathprepend () {
    if [[ ":$PATH:" != *":$1:"* ]]; then
        PATH="$1${PATH:+":$PATH"}"
    fi
}

PATH从向添加目录~/.profile,Git 没有发现它。请注意,echo $PATH在我使用 Git 的 bash 会话中,确实列出了我的目录,我注意到,只是因为我使用了diff-highlight,所以在该目录中建立了符号链接,而在我开始使用上述pathprepend函数后,Git 抱怨diff-highlight缺少了该功能。恢复 POSIX 兼容PATH设置后,它恢复正常工作。

这让我想知道程序使用什么来读取它们的环境。它们是否都带有自己的机制来执行此操作?它们是否将工作留给某个系统 shell 或库?


编辑

@Bodo,这是我以前常做的~/.profile:

pathprepend () {
    if [[ ":$PATH:" != *":$1:"* ]]; then
        PATH="$1${PATH:+":$PATH"}"
    fi
}

pathprepend "$HOME/.local/bin"

我说的“POSIX 兼容”是指没有任何暴力倾向。这是我现在所拥有的~/.profile:

pathprepend () {
  case ":$PATH:" in
    *":$1:"*)
      :;;
    *)
      PATH="$1${PATH:+":$PATH"}";;
  esac
}

pathprepend "$HOME/.local/bin"

两种情况下均~/.profile来源于~/.bash_profile,其中包含

# Load the configuration for login sessions of any shell
if [[ -f "$HOME/.profile" ]]; then
  source "$HOME/.profile"
else
  echo >&2 "$HOME/.bash_profile: $HOME/.profile not found"
fi

# Load the configuration for interactive non-login Bash sessions
case "$-" in *i*)
  if [[ -f "$HOME/.bashrc" ]]; then
    source "$HOME/.bashrc"
  else
    echo >&2 "$HOME/.bash_profile: $HOME/.bashrc not found"
  fi;;
esac

我没有这样做export PATH,因为 Gordon Davisson 在我从中复制函数的答案中解释说“PATH应该已经标记为已导出,因此不需要重新导出。” 事实上,我仍然不知道,export但使用case的版本pathprepend一切正常。顺便问一下,Git 进程的父进程是什么,它是我使用的 Bash 进程吗git?

shell-script
  • 1 个回答
  • 878 Views
Martin Hope
U. Windl
Asked: 2025-03-13 19:38:34 +0800 CST

在脚本中使用“mktemp”构建示例树会产生错误“mktemp:无法通过模板创建文件”和“模糊重定向”

  • 5

我正在尝试为与 NFS 相关的错误创建一个测试用例,每当我检查它时,它rm -rf都会失败并显示“目录不为空”。但是,简单的测试脚本无法重现该错误,因此我尝试编写一个脚本来创建一些目录树,用文件填充它,然后删除该树。由于我怀疑问题与某些文件名缓存有关,因此我使用它mktemp来创建这样的随机名称:

#!/bin/sh
set -x
readonly LEVELS=6
readonly BASE_DIR=test-dir
DIR="$BASE_DIR"
for (( level=0; level < LEVELS; ++level ))
do
    if (( level > 0 )); then
        DIR="$(mktemp -p "$DIR")" || exit
    else
        mkdir "$DIR" || exit
    fi
    for (( i=0; i < 4; ++i ))
    do
        date > $(mktemp -p "$DIR") || exit
    done
    sleep 0.5
done
rm -rf "$BASE_DIR"

然而,脚本以一种我无法理解的方式失败了,如下所示:

> ./test-script.sh
+ readonly LEVELS=6
+ LEVELS=6
+ readonly BASE_DIR=test-dir
+ BASE_DIR=test-dir
+ DIR=test-dir
+ (( level=0 ))
+ (( level < LEVELS ))
+ ((  level > 0  ))
+ mkdir test-dir
+ (( i=0 ))
+ (( i < 4 ))
+ date
++ mktemp -p test-dir
+ (( ++i  ))
+ (( i < 4 ))
+ date
++ mktemp -p test-dir
+ (( ++i  ))
+ (( i < 4 ))
+ date
++ mktemp -p test-dir
+ (( ++i  ))
+ (( i < 4 ))
+ date
++ mktemp -p test-dir
+ (( ++i  ))
+ (( i < 4 ))
+ sleep 0.5
+ (( ++level  ))
+ (( level < LEVELS ))
+ ((  level > 0  ))
++ mktemp -p test-dir
+ DIR=test-dir/tmp.iIbUu2ZDDN
+ (( i=0 ))
+ (( i < 4 ))
+ date
++ mktemp -p test-dir/tmp.iIbUu2ZDDN
mktemp: failed to create file via template ‘test-dir/tmp.iIbUu2ZDDN/tmp.XXXXXXXXXX’: Not a directory
./test-script.sh: line 15: $(mktemp -p "$DIR"): ambiguous redirect
+ exit

所以mktemp -p test-dir没有问题,但mktemp -p test-dir/tmp.iIbUu2ZDDN有。这可能是 中的错误mktemp,还是看起来像我实际上正在寻找的错误?

我知道我的使用mktemp有点不典型,但无论如何。二进制文件来自coreutils-8.32-150400.9.6.1.x86_64(SLES15 SP6)。

列出失败后的目录我看到:

r> ll test-dir/
total 16
-rw------- 1 windl dvmed 32 Mar 13 12:03 tmp.gbslFgK2eD
-rw------- 1 windl dvmed  0 Mar 13 12:03 tmp.iIbUu2ZDDN
-rw------- 1 windl dvmed 32 Mar 13 12:03 tmp.lR5NM8zLtb
-rw------- 1 windl dvmed 32 Mar 13 12:03 tmp.p5Xcfqa3Xr
-rw------- 1 windl dvmed 32 Mar 13 12:03 tmp.YRELcRCk6G

我猜测“模糊重定向”是由于mktemp未能创建有效的文件名造成的。

shell-script
  • 2 个回答
  • 31 Views
Martin Hope
Dimitrios Desyllas
Asked: 2025-03-11 02:26:57 +0800 CST

为什么在我的脚本中我无法在 Debian 上放置多行文本变更日志条目?

  • 9

我正在使用这个 bash 脚本自动升级我的项目版本:

#!/usr/bin/env bash

CHANGELOG="Changelog.md"
DEBIAN_CHANGELOG="debian/changelog"
UPSTREAM_VERSION=$(cat VERSION)

# Updating entries in rpm files

DEB_RELEASE_NOTES=$(awk '{print "  * " $0}' < RELEASE_NOTES)

echo "Adding new Debian changelog entry for version $UPSTREAM_VERSION."
dch -D unstable -m "$DEB_RELEASE_NOTES" --newversion "$UPSTREAM_VERSION-0debian1-unstable1"

# Prompt user to edit Debian changelog
$EDITOR_CHOICE "$DEBIAN_CHANGELOG"

echo "Version updated successfully: $UPSTREAM_VERSION"

它的作用是同步并将版本放在 rpm 和 debian 包中。但是这个命令:

dch -D unstable -m "$DEB_RELEASE_NOTES" --newversion "$UPSTREAM_VERSION-0debian1-unstable1"

给我带来了一些麻烦,因为在 debian/changelog 中存在以下内容:

mkdotenv (0.2.0-0debian1-unstable1) unstable; urgency=medium

  *   * 1. Split codebase into multiple files.   * 2. Use a seperate
    version file and define built version upon compile.   * 4. [BUGFIX]
    If input file is same as output file copy input file into a
    temporary one.   * 5. Improved Documentation

 -- Dimitrios Desyllas <[email protected]>  Mon, 10 Mar 2025 20:08:00 +0200

该RELEASE_NOTES文件包含:

1. Split codebase into multiple files.
2. Use a seperate version file and define built version upon compile.
4. [BUGFIX] If input file is same as output file copy input file into a temporary one.
5. Improved Documentation

您知道为什么所有行都卡在单个项目符号中吗?

shell-script
  • 2 个回答
  • 371 Views
Martin Hope
finefoot
Asked: 2025-03-09 21:34:27 +0800 CST

在 POSIX shell 脚本函数中,将 stdout 复制到具有命名管道的另一个命令中

  • 9
mkfifo foo
printf %s\\n bar | tee foo &
tr -s '[:lower:]' '[:upper:]' <foo
wait
rm foo

这是我想要执行的操作的有效 POSIX shell 脚本:

  • printf %s\\n bar是产生标准输出的外部程序的象征
  • tr -s '[:lower:]' '[:upper:]'象征着另一个应该接收标准输出并对其执行某些操作的命令
  • tee将 stdout 复制到命名管道 foo

输出符合预期:

bar
BAR

现在我想整理一下代码,让它变成这样external_program | my_function。就像这样:

f() (
  mkfifo foo
  tee foo &
  tr -s '[:lower:]' '[:upper:]' <foo
  wait
  rm foo
)
printf %s\\n bar | f

但现在根本就没有任何输出。

shell-script
  • 2 个回答
  • 58 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    模块 i915 可能缺少固件 /lib/firmware/i915/*

    • 3 个回答
  • Marko Smith

    无法获取 jessie backports 存储库

    • 4 个回答
  • Marko Smith

    如何将 GPG 私钥和公钥导出到文件

    • 4 个回答
  • Marko Smith

    我们如何运行存储在变量中的命令?

    • 5 个回答
  • Marko Smith

    如何配置 systemd-resolved 和 systemd-networkd 以使用本地 DNS 服务器来解析本地域和远程 DNS 服务器来解析远程域?

    • 3 个回答
  • Marko Smith

    dist-upgrade 后 Kali Linux 中的 apt-get update 错误 [重复]

    • 2 个回答
  • Marko Smith

    如何从 systemctl 服务日志中查看最新的 x 行

    • 5 个回答
  • Marko Smith

    Nano - 跳转到文件末尾

    • 8 个回答
  • Marko Smith

    grub 错误:你需要先加载内核

    • 4 个回答
  • Marko Smith

    如何下载软件包而不是使用 apt-get 命令安装它?

    • 7 个回答
  • Martin Hope
    user12345 无法获取 jessie backports 存储库 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl 为什么大多数 systemd 示例都包含 WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky 如何将 GPG 私钥和公钥导出到文件 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll systemctl 状态显示:“状态:降级” 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim 我们如何运行存储在变量中的命令? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S 为什么 /dev/null 是一个文件?为什么它的功能不作为一个简单的程序来实现? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 如何从 systemctl 服务日志中查看最新的 x 行 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - 跳转到文件末尾 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla 为什么真假这么大? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis 在一个巨大的(70GB)、一行、文本文件中替换字符串 2017-12-30 06:58:33 +0800 CST

热门标签

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve