source命令遇到的一些问题

在使用source filename命令的时候遇到了一个问题,我使用下面的命令,却报错了

summer@deyuan-server3:~$ source .bashrc
-sh: source: .bashrc: file not found

.bashrc文件就在当前目录下,怎么会 file not found?一开始我以为是权限的问题,因为用ls -l查看了.bashrc的权限,发现是没有执行的权限的,于是加了执行权限,但是还是不行。
然后,我尝试使用相对路径来执行,就成功了。

source ./.bashrc

为什么使用相对路径就可以呢?
查找了source的使用说明,

source filename [arguments]
Read and execute commands from filename in the current shell environment and return the exit status of the last command exe-cuted from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file-name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the source path option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

从上面可以知道,如果filename里面不包括“/”,那么source会从PATH路径里搜索文件,当bash不在posix模式才会搜索当前目录。
难道我的shell是在POSIX模式吗?什么是POSIX模式?百度一下,也没找到解释,我的认知里,POSIX是一种通用的标准。
虽然还不明白posix mode,但是找到了解决问题的方法:为执行文件加上相对路径或者绝对路径,或者把执行文件所在的目录添加到PATH里
但是,我还有个疑惑,我的印象里,之前我用source命令的时候好像没有加路径,于是我又在另一台Linux上试了一下,不加路径也能够成功执行。同样都是Ubuntu系统,怎么要求不一样呢?
会不会是shell的原因呢?于是,我查看了两台电脑的shell,

summer@deyuan-server3:~$ echo $0
-sh
ubuntu@ip-172-31-30-180:~$ echo $0
-bash

果然,两台电脑的shell不同,报错的那台用的是sh,另一台是bash,于是我改成了bash,果然就OK了

summer@deyuan-server3:~$ bash
summer@deyuan-server3:~$ echo $0
bash
summer@deyuan-server3:~$ source .bashrc
summer@deyuan-server3:~$ 

Shell的两种主要语法类型有Bourne 和C ,这两种语法彼此不兼容,Bourne家族主要包括sh,ksh,Bash,psh,zsh,C家族主要包括csh,tcsh
Bash与sh兼容,Linux一般都是使用Bash作为用户的基本Shell。
Linux支持的Shell我们可以通过查看/etc/shells文件进行查看

summer@deyuan-server3:~$ cat /etc/shells 
# /etc/shells: valid login shells
/bin/sh
/bin/dash
/bin/bash
/bin/rbash

我是用的ssh登录的Linux,为什么默认就是使用的sh呢?
可以查看/etc/passwd文件,在创建用户的时候我的shell类型是sh,所以登录后默认是shell

summer@deyuan-server3:~$ cat /etc/passwd | grep "summer"
summer:x:1007:1007::/home/summer:/bin/sh

用chsh -s /bin/bash命令,把登录shell类型改为bash。如果是管理员,可以直接更改/etc/passwd文件,下次再创建新用户的时候可以指定shell类型(因为默认是用sh),useradd -s /bin/bash {用户昵称}

summer@deyuan-server3:~$ chsh -s /bin/bash
Password: 
summer@deyuan-server3:~$ cat /etc/passwd | grep "summer"
summer:x:1007:1007::/home/summer:/bin/bash
summer@deyuan-server3:~$ 

猜你喜欢

转载自blog.csdn.net/Colorful_lights/article/details/85164507