Chinaunix

标题: 程序cd后不起作用 [打印本页]

作者: minzyyl    时间: 2019-03-12 00:28
标题: 程序cd后不起作用
文件名是jump,存放路径是/home,内容如下:

#!/bin/sh
if [[ $1 == "" ]];then
echo "no input"
elif [[$1 != ""]];then
echo "jump to /tmp and source .cshell"
cd /tmp && source .cshell
fi



运行:
%:jump
%:no input
%: jump dir
%:  jump: line 4: [[dir: command not found

目的是运行jump dir后,可以cd到/tmp目录,且source .cshell   


作者: cfwyy    时间: 2019-03-12 08:48
elif 里中括号少了空格。
如果 要在当前的shell进程里切换目录,应该 用source jump 来运行脚本。因为直接运行脚本 是在子shell进程里运行,相当于只在子进程里切换了目录 ,不会影响到父进程。
作者: 本友会机友会摄友会    时间: 2019-03-12 13:58
提示: 作者被禁止或删除 内容自动屏蔽
作者: Shell_HAT    时间: 2019-03-14 13:41
elif [[ $1 != "" ]];then
空格不能少
作者: minzyyl    时间: 2019-03-14 23:21
cfwyy 发表于 2019-03-12 08:48
elif 里中括号少了空格。如果 要在当前的shell进程里切换目录,应该 用source jump 来运行脚本。因为直接运 ...

嗯,谢谢提醒。


可以不用source吗?  因为我的用法是:jump dir,进入目录并source一个文件,如果改用source的话是不是要: source jump?那怎么确定是jump到dir呢?

另外有朋友提示可以用exec,也试过,好像不行。

以前在一家外包公司,他们就是直接用jump dir实现我上面说的功能,但是当时没有看源代码,不知道怎么实现的。

作者: minzyyl    时间: 2019-03-14 23:26
#!/bin/sh
if [[ $1 == "" ]]; then
echo "no input"
elif [[ $1 != "" ]]; then
echo "jump to dir"
cd /tmp && echo "jump ok"
fi


[a0003@as001 ~]$ pwd
/home/a0003
[a0003@as001 ~]$ ./test.sh
no input
[a0003@as001 ~]$ ./test.sh dir
jump to dir
jump ok
[a0003@as001 ~]$ pwd
/home/a0003
[a0003@as001 ~]$

作者: minzyyl    时间: 2019-03-14 23:26
本友会机友会摄友会 发表于 2019-03-12 13:58
powershell 没有 多了个空格,少了个空格就不行的问题。实际上,空格,tab,回车的组合,对powershell毫无 ...

朋友,谢谢了,不过回归正题,有办法实现我说的吗?谢谢

作者: cfwyy    时间: 2019-03-15 08:13
回复 5# minzyyl 为什么不行?,把你脚本的参数带上啊。
  1. soure jump dir
复制代码




作者: minzyyl    时间: 2019-03-31 01:14
cfwyy 发表于 2019-03-15 08:13
回复 5# minzyyl 为什么不行?,把你脚本的参数带上啊。

[asa@001 ~]$ pwd
/home/asa
[asa@001 ~]$ ./test.sh
no input
[asa@001 ~]$ source test.sh dir
if: Expression Syntax.
[asa@001 ~]$ more test.sh
#!/bin/sh
if [[ $1 == "" ]]; then
echo "no input"
elif [[ $1 != "" ]]; then
echo "jump to dir"
cd /tmp $$ echo "jump ok"
fi


作者: cfwyy    时间: 2019-04-01 10:35
回复 9# minzyyl

source用法应该是没问题的,你脚本的写的时候 空格什么的要注意一下,有提示你if 语法错误。我用你的改了下,运行是没问题的。
  1. deb@debian:~/桌面$ pwd
  2. /home/deb/桌面
  3. deb@debian:~/桌面$ cat test.sh
  4. #!/bin/sh

  5. if [[ $1 == "" ]];then
  6.         echo "no input"
  7. elif [[ $1 != "" ]];then
  8.         echo "jump to dir"
  9.         cd /tmp
  10.     echo "jump ok"
  11. fi
  12. deb@debian:~/桌面$ source test.sh 123
  13. jump to dir
  14. jump ok
  15. deb@debian:/tmp$ pwd
  16. /tmp
  17. deb@debian:/tmp$
复制代码



作者: minzyyl    时间: 2019-04-01 17:55
cfwyy 发表于 2019-04-01 10:35
回复 9# minzyyl source用法应该是没问题的,你脚本的写的时候 空格什么的要注意一下,有提示你if 语法错误 ...

我把你的代码复制过来了,运行还是一样,奇怪了,我的默认是csh
作者: minzyyl    时间: 2019-04-01 18:14
cfwyy 发表于 2019-04-01 10:35
回复 9# minzyyl source用法应该是没问题的,你脚本的写的时候 空格什么的要注意一下,有提示你if 语法错误 ...

这个关系不大,我后面多试试解决。

另外可以把前面的source包装起来吗?例如只要test.sh dir就能达到目的,不需要加source,简化程序,谢谢

作者: cfwyy    时间: 2019-04-02 08:26
回复 12# minzyyl

我不知道有其它的方法,不用source就用.   一样的。
  1. . test.sh 123
复制代码







欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2