Skip to main content

Instagram media ID to shortcode

HTML

I wanted a bash solution to convert Instagram media ID numbers to the shortcode they use for their posts. This seems to work pretty well so I'll share it here in case anyone needs it.

Big thanks to mokoshalb's instagramid.php, which helped me figure out how to do this.

 

media_id_to_shortcode () {
	media_id=$1
	alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
	shortcode=
	binary_media_id=$( echo "obase=2;$media_id" | bc )
	pad=$(( 6 - ( ${#binary_media_id} % 6 ) )) 
	if [[ $pad == 6 ]]; then
		pad=0
	fi
	len=$(( ${#binary_media_id} + $pad ))
	binary_media_id=$(printf "%0*s\n" "$len" $binary_media_id)
	for (( i=0 ; i<(( $len - 1 )); i+=6 )); do
		chunk=${binary_media_id:$i:6}
		digit="$((2#$chunk))"
		shortcode="$shortcode${alphabet:$digit:1}"
	done
	echo "$shortcode"
}

Comments