简体   繁体   中英

Set shell script Variable to output of command

Im trying to cd into the md5 hash of whatever variable is set into the script but I do not get the correct value of md5, I think it has something to do with how I'm declaring my variables. Thank you for any help!

#!/bin/bash
var1=$1
md5=$(-n $var1 | md5sum)
cd /var/www/html/$md5

I expected it to take me to a directory given by the md5 hash:

$ ./myscript hello
(no output)
$ pwd
/var/www/html/5d41402abc4b2a76b9719d911017c592

Instead, it gives me errors and tries to cd to the wrong path:

$ ./myscript hello
./myscript: line 3: -n: command not found
./myscript: line 4: cd: /var/www/html/d41d8cd98f00b204e9800998ecf8427e: No such file or directory
$ pwd
/home/me

The md5sum it incorrectly tries to cd to is also the same no matter which value I input.

This works as a solution for anyone else having this issue

#!/bin/bash
md5=$*
hash="$(echo -n "$md5" | md5sum )"
cd /var/www/html/$hash

Your script:

#!/bin/bash
var1=$1
md5=$(-n $var1 | md5sum)
cd /var/www/html/$md5

This has a few issues:

  1. -n is not a valid command in the pipeline -n $var1 | md5sum -n $var1 | md5sum .
  2. md5sum returns more than just the MD5 digest.
  3. Changing the directory in a script will not be reflected in the calling shell.
  4. Input is used unquoted.

I would write a shell function for this, rather than a script:

function md5cd {
  dir="$( printf "%s" "$1" | md5sum - | cut -d ' ' -f 1 )"
  cd /var/www/html/"$dir" || return 1
}

The function computes the MD5 digest of the given string using md5sum and cuts off the filename ( - ) that's part of the output. It then changes directory to the specified location. If the target directory does not exist, it signals this by returning a non-zero exit status.

Extending it to cd to a path constructed from the path on the command line, but with the last path element changed into a MD5 digest (just for fun):

function md5cd {
  word="${1##*/}"

  if [[ "$word" == "$1" ]]; then
    prefix="."
  else
    prefix="${1%/*}"
  fi

  dir="$( cut -d ' ' -f 1 <( printf "%s" "$word" | md5sum - ) )"
  cd "$prefix"/"$dir" || return 1
}

Testing it:

$ pwd
/home/myself

$ echo -n "hex this" | md5sum
990c0fc93296f9eed6651729c1c726d4  -

$ mkdir /tmp/990c0fc93296f9eed6651729c1c726d4

$ md5cd /tmp/"hex this"

$ pwd
/tmp/990c0fc93296f9eed6651729c1c726d4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM