Fra*_*cis 35 linux bash debian
我有 debian 挤压 amd64。我当前的外壳是 bash。如果我在终端中编写以下内容,它会起作用:
$ uname -a
Linux core 2.6.32-5-amd64 #1 SMP Fri May 10 08:43:19 UTC 2013 x86_64 GNU/Linux
$ echo $SHELL
/bin/bash
$ echo $(realpath test.sh)
/home/ffortier/test.sh
Run Code Online (Sandbox Code Playgroud)
我的 test.sh 文件如下所示:
#!/bin/bash
echo $(realpath "$1")
Run Code Online (Sandbox Code Playgroud)
如果我尝试执行以下操作,则会出现错误
$ ./test.sh test.sh
./test.sh: line 2: realpath: command not found
Run Code Online (Sandbox Code Playgroud)
如何在 bash 文件中使用 realpath 命令?
附加信息
$ type -a realpath
realpath is a function
realpath ()
{
f=$@;
if [ -d "$f" ]; then
base="";
dir="$f";
else
base="/$(basename "$f")";
dir=$(dirname "$f");
fi;
dir=$(cd "$dir" && /bin/pwd);
echo "$dir$base"
}
Run Code Online (Sandbox Code Playgroud)
Gil*_*il' 31
至少有两个程序称为realpath
:
readlink -f
. 它现在已被弃用,而支持readlink -f
,因此许多发行版已停止携带它。realpath
程序在 GNU coreutils 8.15 中引入。这太老了,不能被 Debian 挤压甚至喘不过气来;在撰写本文时,Debian 不稳定版也未发布。这个程序非常接近readlink -f
.出于某种原因,您有一个 shell 函数,它部分模拟了realpath
. 这种模拟是部分的:如果你在符号链接上调用它,它不会跟随符号链接。
由于这是一个 shell 函数,大概是从 或 通过 加载的.bashrc
,因此它仅可用于在交互式 shell 中运行的代码。如果您希望它对其他程序可用,假设您正在运行 Linux,请创建一个模拟realpath
以下内容的脚本:
#!/bin/sh
readlink -f -- "$@"
Run Code Online (Sandbox Code Playgroud)
(这不会模拟realpath
很少使用的命令行选项。)
ken*_*orb 18
It works only in shell, because script file has different scope and doesn't have access to your local functions and aliases defined in your rc files. And realpath
command actually doesn't exist in your system.
So either install realpath
from the package, define your own function (as part of the script, check some examples) or source the rc file in your script where it's defined (e.g. . ~/.bashrc
).
Here are the steps to install realpath
if it's not present:
sudo apt-get install coreutils
brew install coreutils
On Debian or Ubuntu it seems the realpath
should be installed by default. I've checked in the recent Debian 8 (Jessie) and it seems to have coreutils
installed by default.
Tested using fresh VM images:
$ vagrant init debian/jessie64 && vagrant up --provider virtualbox && vagrant ssh
$ vagrant init ubuntu/vivid64 && vagrant up --provider virtualbox && vagrant ssh
Run Code Online (Sandbox Code Playgroud)
Then in VM:
$ type -a realpath
realpath is /usr/bin/realpath
Run Code Online (Sandbox Code Playgroud)
Instead of realpath
, you can also use readlink -f file
(or greadlink
) provided by coreutils
package as well.
slm*_*slm 10
realpath 是实际命令还是脚本?我会检查它是从哪里来的。
$ type -a realpath
Run Code Online (Sandbox Code Playgroud)
我不熟悉这个工具,所以它可能不是您的正常发行版的一部分,也许它安装在一个非标准位置,该位置不存在于 Bash 上,$PATH
但在您登录环境的$PATH
.
在任何情况下,上面的type
命令都会向您显示命令的来源,此时您可以像这样更改在脚本中调用它的方法:
echo $(/path/to/realpath test.sh)
Run Code Online (Sandbox Code Playgroud)
或者修改您的脚本$PATH
,使其也包含此非标准位置。
当您调用 shell 脚本时,您的大部分环境都不会被调用。如果您考虑一下,这很有意义,因为您通常不希望脚本具有用户环境可能具有的所有额外负担。
您可以确定哪个源文件提供此功能并获取它的来源,或者只是指示 Bash 合并您的登录环境。
#!/bin/bash -l
echo $(realpath "$1")
Run Code Online (Sandbox Code Playgroud)