Re: Bash: how do I read a file into a variable and keep the line feeds?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi.

On Tue, 24 Jun 2025 23:10:13 -0700
ToddAndMargo via users <users@xxxxxxxxxxxxxxxxxxxxxxx> wrote:
 
> Mail () {
>       local Subject=$1
>       local Body=$2   # note: if $2 starts with "file:" the file will
> be use instead
>       local Cmd=""
>       local Cmd2=""
> 
> ...
> 
>           if [[ "$Body" =~ ^file:.* ]]; then
>               x=$(echo $Body | sed -e 's/^file://')
> 	     Cmd2="cat $x | mailx -s \"$Subject\" $Cmd  $To"
> 
>           else
> 	     Cmd2="echo \"$Body\" | mailx -s \"$Subject\" $Cmd  $To"
>           fi
> 
> 	 echo $Cmd2
> 	 eval $Cmd2
> )

You should really prevent using eval: you may have unexpected results
due to the special characters used by bash. Try for example to put a "
in the Subject.

The =~ construct allows to capture part of the match.

Bash arrays are your friends: "${array[@]}" properly quotes (as does
"$@")

"echo XXX | cmd" == "cmd <<< XXX"

I will thus write this (untested): (I don't use tabs in shell scripts)

    local -a cmd=( mailx -s "$Subject" )
    if [[ "$Body" =~ ^file:(.*) ]]; then
        "${cmd[@]}" -q ${BASH_REMATCH[1]} $Cmd $To
    else
        "${cmd[@]}" $Cmd $To <<< "$Body"
    fi

-- 
francis

-- 
_______________________________________________
users mailing list -- users@xxxxxxxxxxxxxxxxxxxxxxx
To unsubscribe send an email to users-leave@xxxxxxxxxxxxxxxxxxxxxxx
Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/
List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines
List Archives: https://lists.fedoraproject.org/archives/list/users@xxxxxxxxxxxxxxxxxxxxxxx
Do not reply to spam, report it: https://pagure.io/fedora-infrastructure/new_issue



[Index of Archives]     [Older Fedora Users]     [Fedora Announce]     [Fedora Package Announce]     [EPEL Announce]     [EPEL Devel]     [Fedora Magazine]     [Fedora Summer Coding]     [Fedora Laptop]     [Fedora Cloud]     [Fedora Advisory Board]     [Fedora Education]     [Fedora Security]     [Fedora Scitech]     [Fedora Robotics]     [Fedora Infrastructure]     [Fedora Websites]     [Anaconda Devel]     [Fedora Devel Java]     [Fedora Desktop]     [Fedora Fonts]     [Fedora Marketing]     [Fedora Management Tools]     [Fedora Mentors]     [Fedora Package Review]     [Fedora R Devel]     [Fedora PHP Devel]     [Kickstart]     [Fedora Music]     [Fedora Packaging]     [Fedora SELinux]     [Fedora Legal]     [Fedora Kernel]     [Fedora OCaml]     [Coolkey]     [Virtualization Tools]     [ET Management Tools]     [Yum Users]     [Yosemite News]     [Gnome Users]     [KDE Users]     [Fedora Art]     [Fedora Docs]     [Fedora Sparc]     [Libvirt Users]     [Fedora ARM]

  Powered by Linux