shell脚本:改变工作目录,并在文件夹名称空间 [英] Shell script : changing working dir and spaces in folder name
问题描述
我想打一个脚本,需要一个文件路径参数,和CD到它的文件夹中。
这里是我做了什么:
I want to make a script that takes a file path for argument, and cds into its folder. Here is what I made :
#!/bin/bash
#remove the file name, and change every space into \space
shorter=`echo "$1" | sed 's/\/[^\/]*$//' | sed 's/\ /\\\ /g'`
echo $shorter
cd $shorter
其实我有2个问题(我是一个相对的新手到shell脚本):
I actually have 2 questions (I am a relative newbie to shell scripts) :
-
我如何才能让光盘老大难?我想把这个脚本到/ usr / bin,然后再从任何地方在文件系统中调用它。在脚本的回报,我想留在
$短
文件夹中。基本上,如果PWD是在/ usr / bin中,我可以通过键入做到这一点。脚本/我的/路径
而不是./脚本/我的/路径
,但如果我在其他文件夹?
How could I make the cd "persistent" ? I want to put this script into /usr/bin, and then call it from wherever in the filesystem. Upon return of the script, I want to stay in the
$shorter
folder. Basically, if pwd was /usr/bin, I could make it by typing. script /my/path
instead of./script /my/path
, but what if I am in an other folder ?
第二个问题是棘手。每当有在给定参数的空间我的脚本失败。虽然 $短
是我想要的东西(比如 /家庭/插孔/我\\文件夹/子文件夹
),CD蒙山失败误差的/ usr / bin中/脚本:4号线:CD:/家庭/插孔/我的\\:没有这种类型的文件或文件夹
。我想我已经尝试了一切,因此,使用像 CD'$短
或 CD'$短'
于事无补。我在想什么?
The second question is trickier. My script fails whenever there is a space in the given argument. Although $shorter
is exactly what I want (for instance /home/jack/my\ folder/subfolder
), cd fails whith the error /usr/bin/script : line 4 : cd: /home/jack/my\: no file or folder of this type
. I think I have tried everything, using things like cd '$shorter'
or cd "'"$shorter"'"
doesn't help. What am I missing ??
非常感谢你的答案
推荐答案
在的.bashrc
添加以下行:
function shorter() { cd "${1%/*}"; }
-
%
表示,从年底 删除小格局 -
/ *
是百通 %
means remove the smaller pattern from the end/*
is the patern
然后在你的终端:
$ . ~/.bashrc # to refresh your bash configuration
$ type shorter # to check if your new function is available
shorter is a function
shorter ()
{
cd "${1%/*}"
}
$ shorter ./your/directory/filename # this will move to ./your/directory
这篇关于shell脚本:改变工作目录,并在文件夹名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!