linux路径标准化

一般情况下我们在实际使用的都是相对路径比如: ./a/../d
所谓标准化:这里是我自己给他命的名,或许叫相对路径绝对化更准确点。其实就是算出路径的最短表示法,就是把 当前目录和上层目录给去掉,得到最短路径。
比如 /usr/lib/./../ 得到 /usr
方式一:

直接使用cd 然后打印当前路径。SHELL如下:

#!/bin/bash

result=;
arglength=$#;
curarg=0;
curpath=`pwd`
for d in "$@" ; 
do 
	curarg=$curarg+1;
	cd $d;
	result+=`pwd`;
	if [[ $curarg -ne $arglength ]]; 
	then
		result+=" ";
	fi;
done;
cd $curpath;
echo $result;

这种方式简单方便。 我把它命名为 cdnormpath.sh

方式二:
我想能不能够直接使用字符串层面上的操作来计算呢,我们要处理的其实就是两个东西,一个就是 当前目录./ 一个就是 上层目录../
思路很简单 就是对 当前目录 ./ 直接去掉, 对上层目录 ../ 需要这样替换  ./a/b/../ 替换为 ./a/ 就好了。
最终写出如下SHELL:

#!/bin/bash

result=;
arglength=$#;
curarg=0;
for d in "$@" ; 
do 
	curarg=$curarg+1;
	tempd=$d;
	length=${#d};
	if [[ ${d:length-1:length} != "/" ]]; 
	then
		tempd=$tempd"/";
	fi;

	if [[ ${d:0:1} != "/" ]];
	then 
		tempd=$(pwd)"/"$tempd; 
	fi;

	while :;
	do
		tempd1=${tempd//\/.\//\/}; 
		if [[ "$tempd1" = "$tempd" ]]; then
			break;
		fi
		tempd=$tempd1;
	done;

	while :; 
	do 
		tempd1=`echo $tempd |sed 's#/[^/\.]\+/\.\./#/#g'`;
		if [[ ${tempd1:0:4} = "/../" ]]; then
			tempd="";
			break;
		fi;
		if [[ "$tempd1" = "$tempd" ]]; then
			break; 
		fi;
		tempd=$tempd1; 
	done;
	
	if [[ "$tempd" != "" ]] &&[[ "$tempd" != "/" ]];
	then
		length=${#tempd};
		if [[ ${tempd:length-1:1} = "/" ]];
		then
			tempd=${tempd:0:length-1};
		fi;
	fi;
	result+=$tempd;
	if [[ $curarg -ne $arglength ]]; 
	then
		result+=" ";
	fi;
done;
echo $result;

我把它命名为 strnormpath.sh
经测试(只测试了几次)以上两种方式在正常情况下都没问题。
但是在一种情况下 会出偏差:
/../
在这种情况下 第一种方式中 cd 会处理为 /
在第二种方式会认为是非法 返回 空串。
以下为测试结果:
$./cdnormpath.sh / /../  /usr/lib/gcc/ /usr/lib/gcc/././../../   ======>>/ / /usr/lib/gcc /usr
$./strnormpath.sh / /../  /usr/lib/gcc/ /usr/lib/gcc/././../../  ======>>/ (空) /usr/lib/gcc /usr


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值