首页 > 解决方案 > 在bash中调用以base64解码的函数

问题描述

#!/bin/bash

#if there are no args supplied exit with 1
if [ "$#" -eq 0 ]; then
        echo "Unfortunately you have not passed any parameter"
        exit 1
fi

#loop over each argument
for arg in "$@"
do
    if [ -f arg ]; then
                echo "$arg is a file."

                #iterates over the files stated in arguments and reads them    $
                cat $arg | while read line;
                do
                    #should access only first line of the file
                        if [ head -n 1 "$arg" ]; then
                                process line
                                echo "Script has ran successfully!"
                                exit 0
                        #should access only last line of the file
                        elif [ tail -n 1 "$arg" ]; then
                                process line
                                echo "Script has ran successfully!"
                                exit 0
                        #if it accesses any other line of the file
                        else
                                echo "We only process the first and the last line of the file."
                        fi
                done
        else
                exit 2
        fi
done

#function to process the passed string and decode it in base64
process()   {
        string_to_decode = "$1"
        echo "$string_to_decode = " | base64 --decode
}

基本上我希望这个脚本做的是循环传递给脚本的参数,然后如果它是一个文件,那么调用在 base64 中解码的函数,但只是在所选文件的第一行和最后一行。不幸的是,当我运行它时,即使调用了正确的文件,它也什么都不做。if [ head -n 1 "$arg" ]; then我认为这部分代码可能会遇到问题。有任何想法吗?

编辑:所以我明白我实际上只是一遍又一遍地提取第一行,而没有真正将它与任何东西进行比较。所以我尝试将代码的 if 条件更改为:

                    first_line = $(head -n 1 "$arg")
                    last_line = $(tail -n 1 "$arg")
                    if [ first_line == line ]; then
                            process line
                            echo "Script has ran successfully!"
                            exit 0
                    #should access only last line of the file
                    elif [ last_line == line ]; then
                            process line
                            echo "Script has ran successfully!"
                            exit 0

我的目标是遍历文件,例如一个看起来像这样:

MTAxLmdvdi51awo=
MTBkb3duaW5nc3RyZWV0Lmdvdi51awo=
MXZhbGUuZ292LnVrCg==

并解码每个文件的第一行和最后一行。

标签: linuxbashfilebase64

解决方案


要解码提供给脚本的每个文件的第一行和最后一行,请使用以下命令:

#! /bin/bash  
for file in "$@"; do
  [ -f "$file" ] || exit 2
  head -n1 "$file" | base64 --decode
  tail -n2 "$file" | base64 --decode
done

推荐阅读