使用 Bash 自动将最后一个命令的输出捕获到变量中?

发布于 2024-11-06 06:43:58 字数 611 浏览 0 评论 0原文

我希望能够在后续命令中使用上次执行命令的结果。例如,

$ find . -name foo.txt
./home/user/some/directory/foo.txt

现在假设我希望能够在编辑器中打开该文件,或者删除它,或者用它做其他事情,例如

mv <some-variable-that-contains-the-result> /some/new/location

我该怎么做?也许使用一些 bash 变量?

更新:

澄清一下,我不想手动分配事情。我想要的是类似内置 bash 变量的东西,例如

ls /tmp
cd $_

$_ 保存上一个命令的最后一个参数。我想要类似的东西,但带有最后一个命令的输出。

最终更新:

赛斯的回答非常有效。需要记住的几件事:

  • 第一次尝试该解决方案时,不要忘记触摸 /tmp/x ,
  • 只有最后一个命令的退出代码成功时才会存​​储结果

I'd like to be able to use the result of the last executed command in a subsequent command. For example,

$ find . -name foo.txt
./home/user/some/directory/foo.txt

Now let's say I want to be able to open the file in an editor, or delete it, or do something else with it, e.g.

mv <some-variable-that-contains-the-result> /some/new/location

How can I do it? Maybe using some bash variable?

Update:

To clarify, I don't want to assign things manually. What I'm after is something like built-in bash variables, e.g.

ls /tmp
cd $_

$_ holds the last argument of the previous command. I want something similar, but with the output of the last command.

Final update:

Seth's answer has worked quite well. Couple of things to bear in mind:

  • don't forget to touch /tmp/x when trying the solution for the very first time
  • the result will only be stored if last command's exit code was successful

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

我喜欢麦丽素 2024-11-13 06:43:59

有不止一种方法可以做到这一点。一种方法是使用v=$(command),它将命令的输出分配给v。例如:

v=$(date)
echo $v

您也可以使用反引号。

v=`date`
echo $v

来自 Bash 初学者指南

当使用旧式反引号替换形式时,反斜杠保留其字面含义,除非后面跟有“$”、“`”或“\”。前面没有反斜杠的第一个反引号终止命令替换。当使用“$(COMMAND)”形式时,括号内的所有字符组成命令;没有人受到特殊对待。

编辑:在问题中进行编辑后,似乎这不是OP正在寻找的东西。据我所知,没有像 $_ 这样的特殊变量用于最后一个命令的输出。

There are more than one ways to do this. One way is to use v=$(command) which will assign the output of command to v. For example:

v=$(date)
echo $v

And you can use backquotes too.

v=`date`
echo $v

From Bash Beginners Guide,

When the old-style backquoted form of substitution is used, backslash retains its literal meaning except when followed by "$", "`", or "\". The first backticks not preceded by a backslash terminates the command substitution. When using the "$(COMMAND)" form, all characters between the parentheses make up the command; none are treated specially.

EDIT: After the edit in the question, it seems that this is not the thing that the OP is looking for. As far as I know, there is no special variable like $_ for the output of last command.

〆凄凉。 2024-11-13 06:43:59

这很容易。使用反引号:

var=`find . -name foo.txt`

然后您可以在将来随时使用它

echo $var
mv $var /somewhere

It's quite easy. Use back-quotes:

var=`find . -name foo.txt`

And then you can use that any time in the future

echo $var
mv $var /somewhere
风尘浪孓 2024-11-13 06:43:59

我认为您也许能够破解一个解决方案,该解决方案涉及将 shell 设置为包含以下内容的脚本:

#!/bin/sh
bash | tee /var/log/bash.out.log

然后,如果您设置 $PROMPT_COMMAND 来输出分隔符,您可以编写一个辅助函数(可能称为 _) 可以获取该日志的最后一块,因此您可以像以下那样使用它:

% find lots*of*files
...
% echo "$(_)"
... # same output, but doesn't run the command again

I think you might be able to hack out a solution that involves setting your shell to a script containing:

#!/bin/sh
bash | tee /var/log/bash.out.log

Then if you set $PROMPT_COMMAND to output a delimiter, you can write a helper function (maybe called _) that gets you the last chunk of that log, so you can use it like:

% find lots*of*files
...
% echo "$(_)"
... # same output, but doesn't run the command again
十雾 2024-11-13 06:43:59

您可以在 bash 配置文件中设置以下别名:

alias s='it=$($(history | tail -2 | head -1 | cut -d" " -f4-))'

然后,通过在任意命令后键入“s”,您可以将结果保存到 shell 变量“it”中。

所以示例用法是:

$ which python
/usr/bin/python
$ s
$ file $it
/usr/bin/python: symbolic link to `python2.6'

You could set up the following alias in your bash profile:

alias s='it=$($(history | tail -2 | head -1 | cut -d" " -f4-))'

Then, by typing 's' after an arbitrary command you can save the result to a shell variable 'it'.

So example usage would be:

$ which python
/usr/bin/python
$ s
$ file $it
/usr/bin/python: symbolic link to `python2.6'
橪书 2024-11-13 06:43:59

使用反引号捕获输出:

output=`program arguments`
echo $output
emacs $output

Capture the output with backticks:

output=`program arguments`
echo $output
emacs $output
撧情箌佬 2024-11-13 06:43:59

我刚刚从这里的建议中提取了这个 bash 函数:

grab() {     
  grab=$("$@")
  echo $grab
}

然后,你只需执行:

> grab date
Do 16. Feb 13:05:04 CET 2012
> echo $grab
Do 16. Feb 13:05:04 CET 2012

更新:匿名用户建议将 echo 替换为 printf '%s\n' 的优点是它不会处理抓取文本中的 -e 等选项。因此,如果您预计或遇到此类特殊情况,请考虑此建议。另一种选择是使用 cat <<<$grab 代替。

I just distilled this bash function from the suggestions here:

grab() {     
  grab=$("$@")
  echo $grab
}

Then, you just do:

> grab date
Do 16. Feb 13:05:04 CET 2012
> echo $grab
Do 16. Feb 13:05:04 CET 2012

Update: an anonymous user suggested to replace echo by printf '%s\n' which has the advantage that it doesn't process options like -e in the grabbed text. So, if you expect or experience such peculiarities, consider this suggestion. Another option is to use cat <<<$grab instead.

我还不会笑 2024-11-13 06:43:59

通过说“我希望能够在后续命令中使用最后执行的命令的结果”,我假设 - 你的意思是任何命令的结果,而不仅仅是查找。

如果那就是case - xargs 就是您正在寻找的。

<代码>查找 . -名称 foo.txt -print0 | xargs -0 -I{} mv {} /some/new/location/{}

或者,如果您有兴趣先查看输出:

find . -name foo.txt -print0

!! | xargs -0 -I{} mv {} /some/new/location/{}

此命令处理多个文件,即使路径和/或文件名包含空格,它也能发挥作用。

请注意命令的 mv {} /some/new/location/{} 部分。该命令是针对先前命令打印的每一行构建和执行的。此处,先前命令打印的行被替换为 {}

xargs 手册页摘录:

xargs - 从标准输入构建和执行命令行

有关更多详细信息,请参阅手册页:
man xargs

By saying "I'd like to be able to use the result of the last executed command in a subsequent command", I assume - you mean the result of any command, not just find.

If thats the case - xargs is what you are looking for.

find . -name foo.txt -print0 | xargs -0 -I{} mv {} /some/new/location/{}

OR if you are interested to see the output first:

find . -name foo.txt -print0

!! | xargs -0 -I{} mv {} /some/new/location/{}

This command deals with multiple files and works like a charm even if the path and/or filename contains space(s).

Notice the mv {} /some/new/location/{} part of the command. This command is build and executed for each line printed by earlier command. Here the line printed by earlier command is replaced in place of {}.

Excerpt from man page of xargs:

xargs - build and execute command lines from standard input

For more detail see man page:
man xargs

花期渐远 2024-11-13 06:43:59

我通常会按照这里其他人的建议去做......没有作业:

$find . -iname '*.cpp' -print
./foo.cpp
./bar.cpp
$vi `!!`
2 files to edit

如果你愿意,你可以变得更奇特:

$grep -R "some variable" * | grep -v tags
./foo/bar/xxx
./bar/foo/yyy
$vi `!!`

I usually do what the others here have suggested ... without the assignment:

$find . -iname '*.cpp' -print
./foo.cpp
./bar.cpp
$vi `!!`
2 files to edit

You can get fancier if you like:

$grep -R "some variable" * | grep -v tags
./foo/bar/xxx
./bar/foo/yyy
$vi `!!`
十年九夏 2024-11-13 06:43:59

如果您想要的只是重新运行最后一个命令并获取输出,一个简单的 bash 变量就可以工作:

LAST=`!!`

那么您可以在输出上运行命令:

yourCommand $LAST

这将生成一个新进程并重新运行您的命令,然后为您提供输出。听起来您真正想要的是用于命令输出的 bash 历史文件。这意味着您需要捕获 bash 发送到终端的输出。您可以编写一些内容来监视 /dev 或 /proc 所需的内容,但这很混乱。您还可以在您的术语和 bash 之间创建一个“特殊管道”,并在中间使用 tee 命令重定向到您的输出文件。

但这两种解决方案都有些古怪。我认为最好的办法是 terminator 这是一个带有输出日志记录的更现代的终端。只需检查日志文件中最后一个命令的结果即可。与上面类似的 bash 变量将使这变得更加简单。

If all you want is to rerun your last command and get the output, a simple bash variable would work:

LAST=`!!`

So then you can run your command on the output with:

yourCommand $LAST

This will spawn a new process and rerun your command, then give you the output. It sounds like what you would really like would be a bash history file for command output. This means you will need to capture the output that bash sends to your terminal. You could write something to watch the /dev or /proc necessary, but that's messy. You could also just create a "special pipe" between your term and bash with a tee command in the middle which redirects to your output file.

But both of those are kind of hacky solutions. I think the best thing would be terminator which is a more modern terminal with output logging. Just check your log file for the results of the last command. A bash variable similar to the above would make this even simpler.

演多会厌 2024-11-13 06:43:59

在执行命令并决定将结果存储在变量中之后,这是一种方法:

$ find . -name foo.txt
./home/user/some/directory/foo.txt
$ OUTPUT=`!!`
$ echo $OUTPUT
./home/user/some/directory/foo.txt
$ mv $OUTPUT somewhere/else/

或者,如果您提前知道需要将结果存储在变量中,则可以使用反引号:

$ OUTPUT=`find . -name foo.txt`
$ echo $OUTPUT
./home/user/some/directory/foo.txt

Here's one way to do it after you've executed your command and decided that you want to store the result in a variable:

$ find . -name foo.txt
./home/user/some/directory/foo.txt
$ OUTPUT=`!!`
$ echo $OUTPUT
./home/user/some/directory/foo.txt
$ mv $OUTPUT somewhere/else/

Or if you know ahead of time that you'll want the result in a variable, you can use backticks:

$ OUTPUT=`find . -name foo.txt`
$ echo $OUTPUT
./home/user/some/directory/foo.txt
俏︾媚 2024-11-13 06:43:59

作为现有答案的替代方案:如果您的文件名可以包含这样的空格,请使用 while

find . -name foo.txt | while IFS= read -r var; do
  echo "$var"
done

正如我所写,只有当您必须在文件名中预期空格时,差异才有意义。

注意:唯一的内置内容不是关于输出,而是关于最后一个命令的状态。

As an alternative to the existing answers: Use while if your file names can contain blank spaces like this:

find . -name foo.txt | while IFS= read -r var; do
  echo "$var"
done

As I wrote, the difference is only relevant if you have to expect blanks in the file names.

NB: the only built-in stuff is not about the output but about the status of the last command.

温暖的光 2024-11-13 06:43:59

你可以使用!!:1。例子:

~]$ ls *.~
class1.cpp~ class1.h~ main.cpp~ CMakeList.txt~ 

~]$ rm !!:1
rm class1.cpp~ class1.h~ main.cpp~ CMakeList.txt~ 


~]$ ls file_to_remove1 file_to_remove2
file_to_remove1 file_to_remove2

~]$ rm !!:1
rm file_to_remove1

~]$ rm !!:2
rm file_to_remove2

you can use !!:1. Example:

~]$ ls *.~
class1.cpp~ class1.h~ main.cpp~ CMakeList.txt~ 

~]$ rm !!:1
rm class1.cpp~ class1.h~ main.cpp~ CMakeList.txt~ 


~]$ ls file_to_remove1 file_to_remove2
file_to_remove1 file_to_remove2

~]$ rm !!:1
rm file_to_remove1

~]$ rm !!:2
rm file_to_remove2
遗弃M 2024-11-13 06:43:59

我有类似的需求,我想将上一个命令的输出用于下一个命令。很像一个| (管道)。
例如

$ which gradle 
/usr/bin/gradle
$ ls -alrt /usr/bin/gradle

类似 -

$ which gradle |: ls -altr {}

解决方案:
创建了这个自定义管道。非常简单,使用 xargs -

$ alias :='xargs -I{}'

基本上不需要为 xargs 创建一个简写,它的工作方式就像魅力一样,而且非常方便。
我只是在 .bash_profile 文件中添加别名。

I had a similar need, in which I wanted to use the output of last command into the next one. Much like a | (pipe).
eg

$ which gradle 
/usr/bin/gradle
$ ls -alrt /usr/bin/gradle

to something like -

$ which gradle |: ls -altr {}

Solution :
Created this custom pipe. Really simple, using xargs -

$ alias :='xargs -I{}'

Basically nothing by creating a short hand for xargs, it works like charm, and is really handy.
I just add the alias in .bash_profile file.

征﹌骨岁月お 2024-11-13 06:43:59

这可以使用文件描述符的魔力和lastpipe shell 选项来完成。

它必须使用脚本完成 - “lastpipe”选项在交互模式下不起作用。

这是我测试过的脚本:

$ cat shorttest.sh 
#!/bin/bash
shopt -s lastpipe

exit_tests() {
    EXITMSG="$(cat /proc/self/fd/0)"
}

ls /bloop 2>&1 | exit_tests

echo "My output is \"$EXITMSG\""


$ bash shorttest.sh 
My output is "ls: cannot access '/bloop': No such file or directory"

我在这里所做的是:

  1. 设置 shell 选项shopt -s lastpipe。这是行不通的
    如果没有这个,您将丢失文件描述符。

  2. 确保我的 stderr 也被 2>&1 捕获

  3. 将输出通过管道传输到函数中,以便可以使用 stdin 文件描述符
    引用。

  4. 通过获取内容来设置变量
    /proc/self/fd/0 文件描述符,即 stdin。

我使用它来捕获脚本中的错误,因此如果命令出现问题,我可以停止处理脚本并立即退出。

shopt -s lastpipe

exit_tests() {
    MYSTUFF="$(cat /proc/self/fd/0)"
    BADLINE=$BASH_LINENO
}

error_msg () {
    echo -e "$0: line $BADLINE\n\t $MYSTUFF"
    exit 1
}

ls /bloop 2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg

这样我就可以添加 2>&1 |退出测试; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg 位于我想要检查的每个命令后面。

现在您可以享受您的输出了!

It can be done using the magic of file descriptors and the lastpipe shell option.

It has to be done with a script - the "lastpipe" option will not work in interactive mode.

Here's the script I've tested with:

$ cat shorttest.sh 
#!/bin/bash
shopt -s lastpipe

exit_tests() {
    EXITMSG="$(cat /proc/self/fd/0)"
}

ls /bloop 2>&1 | exit_tests

echo "My output is \"$EXITMSG\""


$ bash shorttest.sh 
My output is "ls: cannot access '/bloop': No such file or directory"

What I'm doing here is:

  1. setting the shell option shopt -s lastpipe. It will not work
    without this as you will lose the file descriptor.

  2. making sure my stderr also gets captured with 2>&1

  3. piping the output into a function so that the stdin file descriptor can be
    referenced.

  4. setting the variable by getting the contents of the
    /proc/self/fd/0 file descriptor, which is stdin.

I'm using this for capturing errors in a script so if there is a problem with a command I can stop processing the script and exit right away.

shopt -s lastpipe

exit_tests() {
    MYSTUFF="$(cat /proc/self/fd/0)"
    BADLINE=$BASH_LINENO
}

error_msg () {
    echo -e "$0: line $BADLINE\n\t $MYSTUFF"
    exit 1
}

ls /bloop 2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg

In this way I can add 2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg behind every command I care to check on.

Now you can enjoy your output!

旧人九事 2024-11-13 06:43:59

严格来说,这不是 bash 解决方案,但您可以使用 sed 管道来获取先前命令输出的最后一行。

首先让我们看看文件夹“a”中有什么

rasjani@helruo-dhcp022206::~$ find a
a
a/foo
a/bar
a/bat
a/baz
rasjani@helruo-dhcp022206::~$ 

然后,您的 ls 和 cd 示例将变成 sed & 因此,真正的魔力发生在

rasjani@helruo-dhcp022206::~$ cd `find a |sed '$!d'`
rasjani@helruo-dhcp022206::~/a/baz$ pwd
/home/rasjani/a/baz
rasjani@helruo-dhcp022206::~/a/baz$

sed 中,您将任何命令的输出通过管道传输到 sed 中,然后 sed 打印最后一行,您可以将其用作带有反引号的参数。或者您也可以将其与 xargs 结合起来。 (shell 中的“man xargs”是你的朋友)

This is not strictly a bash solution but you can use piping with sed to get the last row of previous commands output.

First lets see what i have in folder "a"

rasjani@helruo-dhcp022206::~$ find a
a
a/foo
a/bar
a/bat
a/baz
rasjani@helruo-dhcp022206::~$ 

Then, your example with ls and cd would turn to sed & piping into something like this:

rasjani@helruo-dhcp022206::~$ cd `find a |sed '$!d'`
rasjani@helruo-dhcp022206::~/a/baz$ pwd
/home/rasjani/a/baz
rasjani@helruo-dhcp022206::~/a/baz$

So, the actual magic happens with sed, you pipe what ever output of what ever command into sed and sed prints the last row which you can use as parameter with back ticks. Or you can combine that to xargs also. ("man xargs" in shell is your friend)

兮颜 2024-11-13 06:43:59

shell 没有类似 perl 的特殊符号来存储最后一个命令的回显结果。

学习在 awk 中使用管道符号。

find . | awk '{ print "FILE:" $0 }'

在上面的例子中你可以这样做:

find . -name "foo.txt" | awk '{ print "mv "$0" ~/bar/" | "sh" }'

The shell doesn't have perl-like special symbols that store the echo result of the last command.

Learn to use the pipe symbol with awk.

find . | awk '{ print "FILE:" $0 }'

In the example above you could do:

find . -name "foo.txt" | awk '{ print "mv "$0" ~/bar/" | "sh" }'
夜司空 2024-11-13 06:43:59
find . -name foo.txt 1> tmpfile && mv `cat tmpfile` /path/to/some/dir/

这是另一种方式,尽管很脏。

find . -name foo.txt 1> tmpfile && mv `cat tmpfile` /path/to/some/dir/

is yet another way, albeit dirty.

反话 2024-11-13 06:43:59

我发现记住将命令的输出通过管道传输到特定文件有点烦人,我的解决方案是 .bash_profile 中的一个函数,它捕获文件中的输出并在需要时返回结果它。

这个的优点是您不必重新运行整个命令(当使用 find 或其他可能很关键的长时间运行的命令时)

很简单,将其粘贴到您的 中。 bash_profile

脚本

# catch stdin, pipe it to stdout and save to a file
catch () { cat - | tee /tmp/catch.out}
# print whatever output was saved to a file
res () { cat /tmp/catch.out }

用法

$ find . -name 'filename' | catch
/path/to/filename

$ res
/path/to/filename

此时,我倾向于只添加 | catch 到我所有命令的末尾,因为这样做没有任何成本,而且它使我不必重新运行需要很长时间才能完成的命令。

另外,如果您想在文本编辑器中打开文件输出,您可以执行以下操作:

# vim or whatever your favorite text editor is
$ vim <(res)

I find remembering to pipe the output of my commands into a specific file to be a bit annoying, my solution is a function in my .bash_profile that catches the output in a file and returns the result when you need it.

The advantage with this one is that you don't have to rerun the whole command (when using find or other long-running commands that can be critical)

Simple enough, paste this in your .bash_profile:

Script

# catch stdin, pipe it to stdout and save to a file
catch () { cat - | tee /tmp/catch.out}
# print whatever output was saved to a file
res () { cat /tmp/catch.out }

Usage

$ find . -name 'filename' | catch
/path/to/filename

$ res
/path/to/filename

At this point, I tend to just add | catch to the end of all of my commands, because there's no cost to doing it and it saves me having to rerun commands that take a long time to finish.

Also, if you want to open the file output in a text editor you can do this:

# vim or whatever your favorite text editor is
$ vim <(res)
寻找一个思念的角度 2024-11-13 06:43:58

我不知道有任何变量可以自动执行此操作。除了复制粘贴结果之外,要做一些事情,您可以重新运行您刚才所做的任何事情,例如,

vim $(!!)

其中 !! 是历史扩展,意味着“上一个命令”。

如果您希望单个文件名中包含空格或其他字符,可能会妨碍正确的参数解析,请引用结果(vim "$(!!)")。不加引号将允许同时打开多个文件,只要它们不包含空格或其他 shell 解析标记即可。

I don't know of any variable that does this automatically. To do something aside from just copy-pasting the result, you can re-run whatever you just did, eg

vim $(!!)

Where !! is history expansion meaning 'the previous command'.

If you expect there to be a single filename with spaces or other characters in it that might prevent proper argument parsing, quote the result (vim "$(!!)"). Leaving it unquoted will allow multiple files to be opened at once as long as they don't include spaces or other shell parsing tokens.

一桥轻雨一伞开 2024-11-13 06:43:58

这是一个非常hacky的解决方案,但它似乎在某些时候大部分有效。在测试过程中,我注意到有时在命令行上获取 ^C 时效果不太好,尽管我确实对其进行了一些调整以使其表现得更好一些。

这个黑客只是一个交互模式黑客,我非常有信心我不会向任何人推荐它。后台命令可能会导致比正常情况更不明确的行为。其他答案是通过编程获得结果的更好方法。


话虽如此,这里是“解决方案”:

PROMPT_COMMAND='LAST="`cat /tmp/x`"; exec >/dev/tty; exec > >(tee /tmp/x)'

设置此 bash 环境变量并根据需要发出命令。 $LAST 通常会包含您要查找的输出:

startide seth> fortune
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve
startide seth> echo "$LAST"
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve

This is a really hacky solution, but it seems to mostly work some of the time. During testing, I noted it sometimes didn't work very well when getting a ^C on the command line, though I did tweak it a bit to behave a bit better.

This hack is an interactive mode hack only, and I am pretty confident that I would not recommend it to anyone. Background commands are likely to cause even less defined behavior than normal. The other answers are a better way of programmatically getting at results.


That being said, here is the "solution":

PROMPT_COMMAND='LAST="`cat /tmp/x`"; exec >/dev/tty; exec > >(tee /tmp/x)'

Set this bash environmental variable and issues commands as desired. $LAST will usually have the output you are looking for:

startide seth> fortune
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve
startide seth> echo "$LAST"
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve
阳光的暖冬 2024-11-13 06:43:58

Bash 是一种丑陋的语言。是的,您可以将输出分配给变量

MY_VAR="$(find -name foo.txt)"
echo "$MY_VAR"

但最好希望您最难的 find 只返回一个结果,并且该结果中没有任何“奇怪”字符,例如回车符或换行符,因为它们在分配给 Bash 变量时会被默默地修改。

但在使用变量时最好小心正确地引用它!

最好直接对文件进行操作,例如使用 find-execdir (查阅手册)。

find -name foo.txt -execdir vim '{}' ';'

或者

find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'

Bash is kind of an ugly language. Yes, you can assign the output to variable

MY_VAR="$(find -name foo.txt)"
echo "$MY_VAR"

But better hope your hardest that find only returned one result and that that result didn't have any "odd" characters in it, like carriage returns or line feeds, as they will be silently modified when assigned to a Bash variable.

But better be careful to quote your variable correctly when using it!

It's better to act on the file directly, e.g. with find's -execdir (consult the manual).

find -name foo.txt -execdir vim '{}' ';'

or

find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'
旧街凉风 2024-11-13 06:43:58

免责声明:

  • 这个答案迟了半年:D
  • 我是一个重度 tmux 用户
  • 你必须在 tmux 中运行你的 shell 才能工作

在 tmux 中运行交互式 shell 时,你可以轻松访问当前显示在终端上的数据。让我们看一下一些有趣的命令:

  • tmux capture-pane:该命令将显示的数据复制到 tmux 的内部缓冲区之一。它可以复制当前不可见的历史记录,但我们现在对此不感兴趣
  • tmux list-buffers:这显示有关捕获的缓冲区的信息。最新的缓冲区编号为 0。
  • tmux show-buffer -b (buffer num):这会在终端上打印给定缓冲区的内容
  • tmux Paste-buffer -b (buffer num) ):这会将给定缓冲区的内容粘贴为输入

是的,这现在为我们提供了很多可能性:)对于我来说,我设置了一个简单的别名: alias L="tmux capture-pane ; tmux showb -b 0 | tail -n 3 | head -n 1" 现在每次我需要访问最后一行时,我只需使用 $(L) 来获取它。

这与程序使用的输出流(stdin 或 stderr)、打印方法(ncurses 等)和程序的退出代码无关 - 只需要显示数据。

Disclamers:

  • This answer is late half a year :D
  • I'm a heavy tmux user
  • You have to run your shell in tmux for this to work

When running an interactive shell in tmux, you can easily access the data currently displayed on a terminal. Let's take a look at some interesting commands:

  • tmux capture-pane: this one copies the displayed data to one of the tmux's internal buffers. It can copy the history that's currently not visible, but we're not interested in that now
  • tmux list-buffers: this displays the info about the captured buffers. The newest one will have the number 0.
  • tmux show-buffer -b (buffer num): this prints the contents of the given buffer on a terminal
  • tmux paste-buffer -b (buffer num): this pastes the contents of the given buffer as input

Yeah, this gives us a lot of possibilities now :) As for me, I set up a simple alias: alias L="tmux capture-pane; tmux showb -b 0 | tail -n 3 | head -n 1" and now every time I need to access the last line i simply use $(L) to get it.

This is independent of the output stream the program uses (be it stdin or stderr), the printing method (ncurses, etc.) and the program's exit code - the data just needs to be displayed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文